質問

Javaの既存のファイルに繰り返しテキストを追加する必要があります。どうすればいいですか?

役に立ちましたか?

解決

これをロギングの目的で実行していますか?その場合、このためのいくつかのライブラリがあります。最も人気のあるのは、 Log4j ログバック

Java 7 +

これを一度だけ行う必要がある場合は、 Filesクラスにより、これが簡単になります。

try {
    Files.write(Paths.get("myfile.txt"), "the text".getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
    //exception handling left as an exercise for the reader
}

注意:上記の方法では、ファイルがまだ存在しない場合は NoSuchFileException がスローされます。また、改行を自動的に追加しません(テキストファイルに追加するときに頻繁に必要です)。 Steve Chambersの回答では、 Files クラスを使用してこれを行う方法を説明しています。

ただし、同じファイルに何度も書き込む場合、上記ではディスク上のファイルを何度も開いたり閉じたりする必要があり、これは遅い操作です。この場合、バッファー付きライターの方が優れています。

try(FileWriter fw = new FileWriter("myfile.txt", true);
    BufferedWriter bw = new BufferedWriter(fw);
    PrintWriter out = new PrintWriter(bw))
{
    out.println("the text");
    //more code
    out.println("more text");
    //more code
} catch (IOException e) {
    //exception handling left as an exercise for the reader
}

注:

  • FileWriter コンストラクターの2番目のパラメーターは、新しいファイルを書き込むのではなく、ファイルに追加するように指示します。 (ファイルが存在しない場合は作成されます。)
  • 高価なライター( FileWriter など)には、 BufferedWriter の使用をお勧めします。
  • PrintWriter を使用すると、おそらく System.out から慣れている println 構文にアクセスできます。
  • ただし、 BufferedWriter および PrintWriter ラッパーは厳密には必要ありません。

古いJava

try {
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true)));
    out.println("the text");
    out.close();
} catch (IOException e) {
    //exception handling left as an exercise for the reader
}

例外処理

古いJavaの堅牢な例外処理が必要な場合、非常に冗長になります:

FileWriter fw = null;
BufferedWriter bw = null;
PrintWriter out = null;
try {
    fw = new FileWriter("myfile.txt", true);
    bw = new BufferedWriter(fw);
    out = new PrintWriter(bw);
    out.println("the text");
    out.close();
} catch (IOException e) {
    //exception handling left as an exercise for the reader
}
finally {
    try {
        if(out != null)
            out.close();
    } catch (IOException e) {
        //exception handling left as an exercise for the reader
    }
    try {
        if(bw != null)
            bw.close();
    } catch (IOException e) {
        //exception handling left as an exercise for the reader
    }
    try {
        if(fw != null)
            fw.close();
    } catch (IOException e) {
        //exception handling left as an exercise for the reader
    }
}

他のヒント

追加するには、フラグを true に設定して fileWriter を使用できます。

try
{
    String filename= "MyFile.txt";
    FileWriter fw = new FileWriter(filename,true); //the true will append the new data
    fw.write("add a line\n");//appends the string to the file
    fw.close();
}
catch(IOException ioe)
{
    System.err.println("IOException: " + ioe.getMessage());
}

try / catchブロックのここでのすべての答えには、finallyブロックに.close()ピースが含まれているべきではありませんか?

マークされた回答の例:

PrintWriter out = null;
try {
    out = new PrintWriter(new BufferedWriter(new FileWriter("writePath", true)));
    out.println("the text");
} catch (IOException e) {
    System.err.println(e);
} finally {
    if (out != null) {
        out.close();
    }
} 

また、Java 7では、 try-を使用できます。 with-resourcesステートメント。宣言されたリソースを自動的に処理するので、宣言されたリソースを閉じるための最終ブロックは必要ありません。

try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("writePath", true)))) {
    out.println("the text");
} catch (IOException e) {
    System.err.println(e);
}

編集-Apache Commons 2.1では、正しい方法は次のとおりです。

FileUtils.writeStringToFile(file, "String to append", true);

最終的にファイルを適切に閉じるように@Kipのソリューションを適合させました:

public static void appendToFile(String targetFile, String s) throws IOException {
    appendToFile(new File(targetFile), s);
}

public static void appendToFile(File targetFile, String s) throws IOException {
    PrintWriter out = null;
    try {
        out = new PrintWriter(new BufferedWriter(new FileWriter(targetFile, true)));
        out.println(s);
    } finally {
        if (out != null) {
            out.close();
        }
    }
}

Kipの回答を少し拡張するには、 これは、ファイルに新しい行を追加するための簡単なJava 7+メソッドです。まだ存在しない場合は作成します

try {
    final Path path = Paths.get("path/to/filename.txt");
    Files.write(path, Arrays.asList("New line to append"), StandardCharsets.UTF_8,
        Files.exists(path) ? StandardOpenOption.APPEND : StandardOpenOption.CREATE);
} catch (final IOException ioe) {
    // Add your own exception handling...
}

注:上記では Files.write テキストのをファイルに書き込むオーバーロード( println コマンドに似ています)。最後にテキストを書き込む(つまり、 print コマンドに似た)ために、別の Files.write オーバーロードを使用して、バイト配列を渡すことができます(例:" mytext" .getBytes(StandardCharsets.UTF_8))。

すべてのシナリオでストリームが適切に閉じられることを確認します。

これらの回答のうち、エラーが発生した場合にファイルハンドルを開いたままにしておく回答がいくつあるのか、少し不安です。答えは https://stackoverflow.com/a/15053443/2498188 はお金にありますが、それは BufferedWriter ()はスローできません。例外が発生した場合、 FileWriter オブジェクトは開いたままになります。

これを行うより一般的な方法で、 BufferedWriter()がスローできるかどうかは関係ありません:

  PrintWriter out = null;
  BufferedWriter bw = null;
  FileWriter fw = null;
  try{
     fw = new FileWriter("outfilename", true);
     bw = new BufferedWriter(fw);
     out = new PrintWriter(bw);
     out.println("the text");
  }
  catch( IOException e ){
     // File writing/opening failed at some stage.
  }
  finally{
     try{
        if( out != null ){
           out.close(); // Will close bw and fw too
        }
        else if( bw != null ){
           bw.close(); // Will close fw too
        }
        else if( fw != null ){
           fw.close();
        }
        else{
           // Oh boy did it fail hard! :3
        }
     }
     catch( IOException e ){
        // Closing the file writers failed for some obscure reason
     }
  }

編集:

Java 7以降、推奨される方法は「リソースで試す」を使用することです。 JVMに対処させます:

  try(    FileWriter fw = new FileWriter("outfilename", true);
          BufferedWriter bw = new BufferedWriter(fw);
          PrintWriter out = new PrintWriter(bw)){
     out.println("the text");
  }  
  catch( IOException e ){
      // File writing/opening failed at some stage.
  }

Java-7では、このようなこともできます:

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

// ----------------------

Path filePath = Paths.get("someFile.txt");
if (!Files.exists(filePath)) {
    Files.createFile(filePath);
}
Files.write(filePath, "Text to be added".getBytes(), StandardOpenOption.APPEND);

java 7 +

私は単純なjavaのファンであるため、私の謙虚な意見では、前述の回答の組み合わせであることを提案します。たぶん私はパーティーに遅れています。コードは次のとおりです。

 String sampleText = "test" +  System.getProperty("line.separator");
 Files.write(Paths.get(filePath), sampleText.getBytes(StandardCharsets.UTF_8), 
 StandardOpenOption.CREATE, StandardOpenOption.APPEND);

ファイルが存在しない場合は作成し、既に存在する場合は追加します sampleText を既存のファイルに追加します。これを使用すると、不要なライブラリをクラスパスに追加する必要がなくなります。

これは、1行のコードで実行できます。これが役に立てば幸いです:)

Files.write(Paths.get(fileName), msg.getBytes(), StandardOpenOption.APPEND);

java.nio。ファイル java.nio.file。 StandardOpenOptionとともに

    PrintWriter out = null;
    BufferedWriter bufWriter;

    try{
        bufWriter =
            Files.newBufferedWriter(
                Paths.get("log.txt"),
                Charset.forName("UTF8"),
                StandardOpenOption.WRITE, 
                StandardOpenOption.APPEND,
                StandardOpenOption.CREATE);
        out = new PrintWriter(bufWriter, true);
    }catch(IOException e){
        //Oh, no! Failed to create PrintWriter
    }

    //After successful creation of PrintWriter
    out.println("Text to be appended");

    //After done writing, remember to close!
    out.close();

Filesを使用して BufferedWriter を作成します。これは StandardOpenOption パラメータを受け入れ、結果の BufferedWriter <から自動フラッシュ PrintWriter / code>。 PrintWriter println()メソッドを呼び出して、ファイルに書き込むことができます。

このコードで使用される StandardOpenOption パラメーター:書き込み用にファイルを開き、ファイルにのみ追加し、存在しない場合はファイルを作成します。

Paths.get(&quot; path here&quot;)は、 new File(&quot; path here&quot;)。toPath()に置き換えることができます。 また、 Charset.forName(&quot; charset name&quot;)は、目的の Charset に合わせて変更できます。

小さな詳細を追加するだけです:

    new FileWriter("outfilename", true)

2.ndパラメーター(true)は、 appendable http://docs.oracle.com/javase/7/docs/api/java/lang/Appendable.html )。特定のファイル/ストリームの最後にコンテンツを追加できるようにします。このインターフェイスは、Java 1.5以降で実装されています。このインターフェイスを持つ各オブジェクト(つまり、 BufferedWriter、CharArrayWriter、CharBuffer、FileWriter、FilterWriter、LogStream、OutputStreamWriter、PipedWriter、PrintStream、PrintWriter、StringBuffer、StringBuilder、StringWriter、Writer )は、コンテンツの追加に使用できます

つまり、gzipされたファイルにいくつかのコンテンツを追加したり、httpプロセスを追加したりできます

グアバを使用したサンプル:

File to = new File("C:/test/test.csv");

for (int i = 0; i < 42; i++) {
    CharSequence from = "some string" + i + "\n";
    Files.append(from, to, Charsets.UTF_8);
}

bufferFileWriter.appendを試してみてください、それは私と一緒に動作します。

FileWriter fileWriter;
try {
    fileWriter = new FileWriter(file,true);
    BufferedWriter bufferFileWriter = new BufferedWriter(fileWriter);
    bufferFileWriter.append(obj.toJSONString());
    bufferFileWriter.newLine();
    bufferFileWriter.close();
} catch (IOException ex) {
    Logger.getLogger(JsonTest.class.getName()).log(Level.SEVERE, null, ex);
}
    String str;
    String path = "C:/Users/...the path..../iin.txt"; // you can input also..i created this way :P

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    PrintWriter pw = new PrintWriter(new FileWriter(path, true));

    try 
    {
       while(true)
        {
            System.out.println("Enter the text : ");
            str = br.readLine();
            if(str.equalsIgnoreCase("exit"))
                break;
            else
                pw.println(str);
        }
    } 
    catch (Exception e) 
    {
        //oh noes!
    }
    finally
    {
        pw.close();         
    }

これにより、目的の処理が実行されます。

try-with-resourcesを使用し、最後にJava 7より前のすべてのビジネスを使用する方が良い

static void appendStringToFile(Path file, String s) throws IOException  {
    try (BufferedWriter out = Files.newBufferedWriter(file, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
        out.append(s);
        out.newLine();
    }
}

Java 7以降を使用しており、ファイルに追加(追加)する内容もわかっている場合は、 NIOパッケージのnewBufferedWriter メソッド。

public static void main(String[] args) {
    Path FILE_PATH = Paths.get("C:/temp", "temp.txt");
    String text = "\n Welcome to Java 8";

    //Writing to the file temp.txt
    try (BufferedWriter writer = Files.newBufferedWriter(FILE_PATH, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
        writer.write(text);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

注意すべき点がいくつかあります:

  1. 文字セットエンコーディングを指定することは常に良い習慣であり、そのために StandardCharsets クラスに定数があります。
  2. コードは、リソースが試行後に自動的に閉じられる try-with-resource ステートメントを使用します。

OPは質問していませんが、特定のキーワードを含む行を検索したい場合に備えて、たとえば confidential JavaのストリームAPIを利用できます:

//Reading from the file the first line which contains word "confidential"
try {
    Stream<String> lines = Files.lines(FILE_PATH);
    Optional<String> containsJava = lines.filter(l->l.contains("confidential")).findFirst();
    if(containsJava.isPresent()){
        System.out.println(containsJava.get());
    }
} catch (IOException e) {
    e.printStackTrace();
}
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class Writer {


    public static void main(String args[]){
        doWrite("output.txt","Content to be appended to file");
    }

    public static void doWrite(String filePath,String contentToBeAppended){

       try(
            FileWriter fw = new FileWriter(filePath, true);
            BufferedWriter bw = new BufferedWriter(fw);
            PrintWriter out = new PrintWriter(bw)
          )
          {
            out.println(contentToBeAppended);
          }  
        catch( IOException e ){
        // File writing/opening failed at some stage.
        }

    }

}
FileOutputStream stream = new FileOutputStream(path, true);
try {

    stream.write(

        string.getBytes("UTF-8") // Choose your encoding.

    );

} finally {
    stream.close();
}

次に、アップストリームのどこかでIOExceptionをキャッチします。

プロジェクト内の任意の場所に関数を作成し、必要なときにその関数を呼び出すだけです。

皆さんは、非同期で呼び出していないアクティブなスレッドを呼び出していることを覚えておく必要があります。適切に処理するには5〜10ページが適していると思われます。 あなたのプロジェクトにより多くの時間を費やし、すでに書かれたものを書くことを忘れないでください。 適切に

    //Adding a static modifier would make this accessible anywhere in your app

    public Logger getLogger()
    {
       return java.util.logging.Logger.getLogger("MyLogFileName");
    }
    //call the method anywhere and append what you want to log 
    //Logger class will take care of putting timestamps for you
    //plus the are ansychronously done so more of the 
    //processing power will go into your application

    //from inside a function body in the same class ...{...

    getLogger().log(Level.INFO,"the text you want to append");

    ...}...
    /*********log file resides in server root log files********/

3行目は実際にテキストを追加するため、実際には3行のコード2。 :P

  

ライブラリ

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
  

コード

public void append()
{
    try
    {
        String path = "D:/sample.txt";

        File file = new File(path);

        FileWriter fileWriter = new FileWriter(file,true);

        BufferedWriter bufferFileWriter  = new BufferedWriter(fileWriter);

        fileWriter.append("Sample text in the file to append");

        bufferFileWriter.close();

        System.out.println("User Registration Completed");

    }catch(Exception ex)
    {
        System.out.println(ex);
    }
}

これも試すことができます:

JFileChooser c= new JFileChooser();
c.showOpenDialog(c);
File write_file = c.getSelectedFile();
String Content = "Writing into file"; //what u would like to append to the file



try 
{
    RandomAccessFile raf = new RandomAccessFile(write_file, "rw");
    long length = raf.length();
    //System.out.println(length);
    raf.setLength(length + 1); //+ (integer value) for spacing
    raf.seek(raf.length());
    raf.writeBytes(Content);
    raf.close();
} 
catch (Exception e) {
    //any exception handling method of ur choice
}
FileOutputStream fos = new FileOutputStream("File_Name", true);
fos.write(data);

trueの場合、既存のファイルにデータを追加できます。書く場合

FileOutputStream fos = new FileOutputStream("File_Name");

既存のファイルを上書きします。最初のアプローチに進みます。

apache commonsプロジェクトをお勧めします。このプロジェクトは、必要なこと(つまり、コレクションの柔軟なフィルタリング)を行うためのフレームワークを既に提供しています。

次の方法では、ファイルにテキストを追加できます。

private void appendToFile(String filePath, String text)
{
    PrintWriter fileWriter = null;

    try
    {
        fileWriter = new PrintWriter(new BufferedWriter(new FileWriter(
                filePath, true)));

        fileWriter.println(text);
    } catch (IOException ioException)
    {
        ioException.printStackTrace();
    } finally
    {
        if (fileWriter != null)
        {
            fileWriter.close();
        }
    }
}

代わりに FileUtilsを使用する

public static void appendToFile(String filePath, String text) throws IOException
{
    File file = new File(filePath);

    if(!file.exists())
    {
        file.createNewFile();
    }

    String fileContents = FileUtils.readFileToString(file);

    if(file.length() != 0)
    {
        fileContents = fileContents.concat(System.lineSeparator());
    }

    fileContents = fileContents.concat(text);

    FileUtils.writeStringToFile(file, fileContents);
}

これは効率的ではありませんが、正常に機能します。改行は正しく処理され、まだ存在しない場合は新しいファイルが作成されます。

このコードはあなたのニーズを満たします:

   FileWriter fw=new FileWriter("C:\\file.json",true);
   fw.write("ssssss");
   fw.close();

特定の行にテキストを追加する場合は、まずファイル全体を読み、必要な場所にテキストを追加してから、次のコードのようにすべてを上書きできます:

public static void addDatatoFile(String data1, String data2){


    String fullPath = "/home/user/dir/file.csv";

    File dir = new File(fullPath);
    List<String> l = new LinkedList<String>();

    try (BufferedReader br = new BufferedReader(new FileReader(dir))) {
        String line;
        int count = 0;

        while ((line = br.readLine()) != null) {
            if(count == 1){
                //add data at the end of second line                    
                line += data1;
            }else if(count == 2){
                //add other data at the end of third line
                line += data2;
            }
            l.add(line);
            count++;
        }
        br.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }       
    createFileFromList(l, dir);
}

public static void createFileFromList(List<String> list, File f){

    PrintWriter writer;
    try {
        writer = new PrintWriter(f, "UTF-8");
        for (String d : list) {
            writer.println(d.toString());
        }
        writer.close();             
    } catch (FileNotFoundException | UnsupportedEncodingException e) {
        e.printStackTrace();
    }
}

私の答え:

JFileChooser chooser= new JFileChooser();
chooser.showOpenDialog(chooser);
File file = chooser.getSelectedFile();
String Content = "What you want to append to file";

try 
{
    RandomAccessFile random = new RandomAccessFile(file, "rw");
    long length = random.length();
    random.setLength(length + 1);
    random.seek(random.length());
    random.writeBytes(Content);
    random.close();
} 
catch (Exception exception) {
    //exception handling
}
/**********************************************************************
 * it will write content to a specified  file
 * 
 * @param keyString
 * @throws IOException
 *********************************************************************/
public static void writeToFile(String keyString,String textFilePAth) throws IOException {
    // For output to file
    File a = new File(textFilePAth);

    if (!a.exists()) {
        a.createNewFile();
    }
    FileWriter fw = new FileWriter(a.getAbsoluteFile(), true);
    BufferedWriter bw = new BufferedWriter(fw);
    bw.append(keyString);
    bw.newLine();
    bw.close();
}// end of writeToFile()

次のコードを使用して、ファイルにコンテンツを追加できます。

 String fileName="/home/shriram/Desktop/Images/"+"test.txt";
  FileWriter fw=new FileWriter(fileName,true);    
  fw.write("here will be you content to insert or append in file");    
  fw.close(); 
  FileWriter fw1=new FileWriter(fileName,true);    
 fw1.write("another content will be here to be append in the same file");    
 fw1.close(); 

1.7アプローチ:

void appendToFile(String filePath, String content) throws IOException{

    Path path = Paths.get(filePath);

    try (BufferedWriter writer = 
            Files.newBufferedWriter(path, 
                    StandardOpenOption.APPEND)) {
        writer.newLine();
        writer.append(content);
    }

    /*
    //Alternative:
    try (BufferedWriter bWriter = 
            Files.newBufferedWriter(path, 
                    StandardOpenOption.WRITE, StandardOpenOption.APPEND);
            PrintWriter pWriter = new PrintWriter(bWriter)
            ) {
        pWriter.println();//to have println() style instead of newLine();   
        pWriter.append(content);//Also, bWriter.append(content);
    }*/
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top