我需要在Java中反复向现有文件追加文本。我怎么做呢?


当前回答

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到现有文件。使用它,可以避免向类路径添加不必要的库。

其他回答

在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到现有文件。使用它,可以避免向类路径添加不必要的库。

    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();         
    }

这将达到你的目的。

我只是补充了一个小细节:

    new FileWriter("outfilename", true)

2.nd parameter (true) is a feature (or, interface) called appendable (http://docs.oracle.com/javase/7/docs/api/java/lang/Appendable.html). It is responsible for being able to add some content to the end of particular file/stream. This interface is implemented since Java 1.5. Each object (i.e. BufferedWriter, CharArrayWriter, CharBuffer, FileWriter, FilterWriter, LogStream, OutputStreamWriter, PipedWriter, PrintStream, PrintWriter, StringBuffer, StringBuilder, StringWriter, Writer) with this interface can be used for adding content

换句话说,您可以向gzip文件或http进程添加一些内容

在项目的任何地方创建一个函数,并在任何需要的地方简单地调用该函数。

伙计们,你们要记住,你们调用的是活动线程,而不是异步调用,因为它可能需要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********/

三行代码,实际上是两行,因为第三行实际上是追加文本。: P