Java文件:追加内容到文本文件

代码如下:

package javalean;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileTest {
    public FileTest() {

    }

    public static void main(String[] args) {
        FileAppendDemo();
    };

    public static void FileAppendDemo() {
        String path = "E:\apks\my.txt";
//        java文件输出流
        FileOutputStream fos = null;
//        File对象代表磁盘中实际存在的文件和目录
        File file = new File(path);
        try {
            if (!file.exists()) {
//                在文件系统中根据保存在文件中的路径信息,创建一个新的空文件。如果创建成功就会返回true,如果文件存在返回false。注意:如果他已经存在但不是文件,可能是目录也会返回false。
                boolean hasFile = file.createNewFile();
                if (!hasFile) {
                    fos = new FileOutputStream(file);
                }
            } else {
//                以追加的方式创建一个文件输出流
                fos = new FileOutputStream(file, true);
            }
            fos.write("test".getBytes());
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

 参考资料:

1.public boolean createNewFile () 解释

https://blog.csdn.net/dajian790626/article/details/8520532?utm_medium=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase

Creates a new, empty file on the file system according to the path information stored in this file. This method returns true if it creates a file, false if the file already existed. Note that it returns false even if the file is not a file (because it's a directory, say).

在文件系统中根据保存在文件中的路径信息,创建一个新的空文件。如果创建成功就会返回true,如果文件存在返回false。注意:如果他已经存在但不是文件,可能是目录也会返回false。

2.file.createNewFile()有实际意义吗?

https://ask.csdn.net/questions/382747

虽然我没有看过FileOutputStream这个类的源代码,但是我估计里面也是掉用了这个方法,有的时候你不使用流,但是也要在某个地方创建文件不就用到了吗,再说流是有开销的,你使用完了还要关,而且根据程序设计原则就是把不同功能的模块区分出来,文件类专门管理文件,文件流专门负责传输文件,这是语言设计,就像高级流关闭之后,包含的低级流也会自动关闭,但是还不是有关闭的方法,你说有什么意义呢

 

原文地址:https://www.cnblogs.com/jycjy/p/13267977.html