用Java创建和写入(文本)文件的最简单方法是什么?


当前回答

以下是编写文件的代码,也在退出帮助内容网页时删除:

public String writeHelpContent(String filePath, String helpPageContent) throws IOException{
        logger.info("HowToUseRiskOfficeHelpService - writeHelpContent start");
        File file = new File(filePath);
        try(FileWriter fw = new FileWriter(file);){
            file.deleteOnExit();
            if(file.createNewFile()) {
                logger.info("HowToUseRiskOfficeHelpService - file created successfully");
            }else {
                logger.info("HowToUseRiskOfficeHelpService - file already exists");
            }
            fw.write(helpPageContent); 
            fw.flush();
        }

        return "Sucessfully write into help page file";
    }

其他回答

请注意,下面的每个代码示例都可能引发IOException。为了简洁起见,省略了Try/catch/finally块。有关异常处理的信息,请参阅本教程。

请注意,如果文件已经存在,下面的每个代码示例都将覆盖该文件

创建文本文件:

PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close();

创建二进制文件:

byte data[] = ...
FileOutputStream out = new FileOutputStream("the-file-name");
out.write(data);
out.close();

Java 7+用户可以使用Files类写入文件:

创建文本文件:

List<String> lines = Arrays.asList("The first line", "The second line");
Path file = Paths.get("the-file-name.txt");
Files.write(file, lines, StandardCharsets.UTF_8);
//Files.write(file, lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND);

创建二进制文件:

byte data[] = ...
Path file = Paths.get("the-file-name");
Files.write(file, data);
//Files.write(file, data, StandardOpenOption.APPEND);

以下是编写文件的代码,也在退出帮助内容网页时删除:

public String writeHelpContent(String filePath, String helpPageContent) throws IOException{
        logger.info("HowToUseRiskOfficeHelpService - writeHelpContent start");
        File file = new File(filePath);
        try(FileWriter fw = new FileWriter(file);){
            file.deleteOnExit();
            if(file.createNewFile()) {
                logger.info("HowToUseRiskOfficeHelpService - file created successfully");
            }else {
                logger.info("HowToUseRiskOfficeHelpService - file already exists");
            }
            fw.write(helpPageContent); 
            fw.flush();
        }

        return "Sucessfully write into help page file";
    }

如果出于某种原因想要将创建和编写行为分开,那么Java中的touch等价物是

try {
   //create a file named "testfile.txt" in the current working directory
   File myFile = new File("testfile.txt");
   if ( myFile.createNewFile() ) {
      System.out.println("Success!");
   } else {
      System.out.println("Failure!");
   }
} catch ( IOException ioe ) { ioe.printStackTrace(); }

createNewFile()执行存在性检查,并自动创建文件。例如,如果您希望在写入文件之前确保自己是文件的创建者,这可能很有用。

在Java 11+中,编写纯文本:

Files.writeString(Path.of("filename.txt"), "some-text");

如果我们使用的是Java7及以上版本,并且还知道要添加(附加)到文件中的内容,我们可以使用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();
    }
}

有几点需要注意:

指定字符集编码总是一个好习惯,因此我们在类StandardCharset中有常量。代码使用try with resource语句,其中资源在try之后自动关闭。

虽然OP没有询问,但为了以防万一我们想搜索具有特定关键字的行,例如机密,我们可以使用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();
}