如何将文本追加到Java中的现有文件 [英] How to append text to an existing file in Java

查看:169
本文介绍了如何将文本追加到Java中的现有文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要重复追加文本到Java中的现有文件。如何做到这一点?

解决方案

如果是这样,有这个的几个库。其中两个最受欢迎的是 Log4j Logback



Java 7 +



需要这样做一次,文件类使得这一点变得简单:

$ p $ try {
Files.write(Paths.get(myfile.txt ),文本.getBytes(),StandardOpenOption.APPEND);
} catch(IOException e){
//将异常处理留作练习读者
}

小心:如果文件不存在,上面的方法会抛出 NoSuchFileException 它也不会自动追加一个换行符(当你追加到一个文本文件时你经常需要这个换行符)。 史蒂夫钱伯斯的答案涵盖了如何使用 Files 类来做到这一点。然而,如果你要多次写入同一个文件,上面必须多次打开和关闭磁盘上的文件,这就是一个缓慢的操作。在这种情况下,一个缓冲的作家是更好的:

$ $ p $ try(FileWriter fw = new FileWriter(myfile.txt,true) ;
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw))
{
out.println(text);
//更多的代码
out.println(more text);
//更多的代码
} catch(IOException e){
//异常处理留给读者练习
}


$ b FileWriter 构造函数的第二个参数会告诉它追加到文件中,而不是写入一个新文件。 (如果该文件不存在,将会被创建。)
  • 对于一个昂贵的编写器(例如,使用 BufferedWriter FileWriter )。

  • 使用 PrintWriter 可以访问 println 语法,您可能习惯于从 System.out

  • BufferedWriter PrintWriter 包装并不是必须的。





    旧版Java



      try {
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(myfile.txt,true)));
    out.println(text);
    out.close();
    } catch(IOException e){
    //将异常处理留作练习读者
    }






    异常处理



    如果您需要对较老的Java进行健壮的异常处理,非常详细:

      FileWriter fw = null; 
    BufferedWriter bw = null;
    PrintWriter out = null;
    尝试{
    fw = new FileWriter(myfile.txt,true);
    bw = new BufferedWriter(fw);
    out = new PrintWriter(bw);
    out.println(text);
    out.close();
    } catch(IOException e){
    //异常处理留给练习读者
    }
    finally {
    try {
    if(out != null)
    out.close();
    } catch(IOException e){
    //将异常处理留给练习读者
    }
    try {
    if(bw!= null)
    bw.close();
    } catch(IOException e){
    //将异常处理作为练习留给读者
    }
    try {
    if(fw!= null)
    fw.close();
    } catch(IOException e){
    //将异常处理留作练习读者
    }
    }


    I need to append text repeatedly to an existing file in Java. How do I do that?

    解决方案

    Are you doing this for logging purposes? If so there are several libraries for this. Two of the most popular are Log4j and Logback.

    Java 7+

    If you just need to do this one time, the Files class makes this easy:

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

    Careful: The above approach will throw a NoSuchFileException if the file does not already exist. It also does not append a newline automatically (which you often want when appending to a text file). Steve Chambers's answer covers how you could do this with Files class.

    However, if you will be writing to the same file many times, the above has to open and close the file on the disk many times, which is a slow operation. In this case, a buffered writer is better:

    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
    }
    

    Notes:

    • The second parameter to the FileWriter constructor will tell it to append to the file, rather than writing a new file. (If the file does not exist, it will be created.)
    • Using a BufferedWriter is recommended for an expensive writer (such as FileWriter).
    • Using a PrintWriter gives you access to println syntax that you're probably used to from System.out.
    • But the BufferedWriter and PrintWriter wrappers are not strictly necessary.

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


    Exception Handling

    If you need robust exception handling for older Java, it gets very verbose:

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

    这篇关于如何将文本追加到Java中的现有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆