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


当前回答

图书馆

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 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
}

您这样做是为了记录日志吗?如果是这样,有几个库。其中最流行的两个是Log4j和Logback。

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。它也不会自动追加换行符(当追加到文本文件时,您经常希望这样)。另一种方法是同时传递CREATE和APPEND选项,如果文件不存在,则会先创建文件:

private void write(final String s) throws IOException {
    Files.writeString(
        Path.of(System.getProperty("java.io.tmpdir"), "filename.txt"),
        s + System.lineSeparator(),
        CREATE, APPEND
    );
}

但是,如果要多次写入同一个文件,那么上面的代码段必须多次打开和关闭磁盘上的文件,这是一个缓慢的操作。在这种情况下,BufferedWriter会更快:

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构造函数的第二个参数将告诉它追加到文件中,而不是写入一个新文件。(如果该文件不存在,将创建该文件。) 对于昂贵的写入器(如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
    }
}

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);
    }*/
}

这段代码将满足您的需要:

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

这可以在一行代码中完成。希望这对你有所帮助。

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