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


当前回答

如果您已经有了要写入文件的内容(而不是动态生成的),那么Java7中作为本机I/O的一部分添加的java.nio.file.Files提供了实现目标的最简单、最有效的方法。

基本上,创建和写入文件只需一行,而且只需一个简单的方法调用!

以下示例创建并写入6个不同的文件,以展示如何使用它:

Charset utf8 = StandardCharsets.UTF_8;
List<String> lines = Arrays.asList("1st line", "2nd line");
byte[] data = {1, 2, 3, 4, 5};

try {
    Files.write(Paths.get("file1.bin"), data);
    Files.write(Paths.get("file2.bin"), data,
            StandardOpenOption.CREATE, StandardOpenOption.APPEND);
    Files.write(Paths.get("file3.txt"), "content".getBytes());
    Files.write(Paths.get("file4.txt"), "content".getBytes(utf8));
    Files.write(Paths.get("file5.txt"), lines, utf8);
    Files.write(Paths.get("file6.txt"), lines, utf8,
            StandardOpenOption.CREATE, StandardOpenOption.APPEND);
} catch (IOException e) {
    e.printStackTrace();
}

其他回答

至少有几种方法可以创建文件并写入其中:

小文件(1.7)

您可以使用其中一种写入方法将字节或行写入文件。

Path file = Paths.get("path-to-file");
byte[] buf = "text-to-write-to-file".getBytes();
Files.write(file, buf);

这些方法为您处理大部分工作,例如打开和关闭流,但不适用于处理大型文件。

使用缓冲流I/O写入更大的文件(1.7)

java.nio.file包支持通道I/O,它可以在缓冲区中移动数据,绕过一些可能阻塞流I/O的层。

String s = "much-larger-text-to-write-to-file";
try (BufferedWriter writer = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) {
    writer.write(s, 0, s.length());
}

这种方法由于其高效的性能,特别是在完成大量写入操作时,是优先的。缓冲操作具有这种效果,因为它们不需要为每个字节调用操作系统的写入方法,从而减少了昂贵的I/O操作。

使用NIOAPI复制(并创建一个新的)带有输出流的文件(1.7)

Path oldFile = Paths.get("existing-file-path");
Path newFile = Paths.get("new-file-path");
try (OutputStream os = new FileOutputStream(newFile.toFile())) {
    Files.copy(oldFile, os);
}

还有其他方法允许将输入流中的所有字节复制到文件中。

FileWriter(文本)(<1.7)

直接写入文件(性能较低),仅当写入次数较少时才应使用。用于将面向字符的数据写入文件。

String s= "some-text";
FileWriter fileWriter = new FileWriter("C:\\path\\to\\file\\file.txt");
fileWriter.write(fileContent);
fileWriter.close();

FileOutputStream(二进制)(<1.7)

FileOutputStream用于写入原始字节流,如图像数据。

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

使用这种方法,应该考虑始终写入字节数组,而不是一次写入一个字节。加速可能非常显著-高达10倍或更高。因此,建议尽可能使用write(byte[])方法。

    public static void writefromFile(ArrayList<String> lines, String destPath) {
        FileWriter fw;
        try {
            fw = new FileWriter(destPath);
            for (String str : lines) {
                fw.write(str);
            }
            fw.close();
         } catch (IOException ex) {
            JOptionPane.showMessageDialog("ERROR: exception was: " + ex.toString());
        }
        File f = new File(destPath);
        f.setExecutable(true);
    }

请注意,下面的每个代码示例都可能引发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);

用Java创建和写入文件的一种非常简单的方法:

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

public class CreateFiles {

    public static void main(String[] args) {
        try{
            // Create new file
            String content = "This is the content to write into create file";
            String path="D:\\a\\hi.txt";
            File file = new File(path);

            // If file doesn't exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }

            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);

            // Write in file
            bw.write(content);

            // Close connection
            bw.close();
        }
        catch(Exception e){
            System.out.println(e);
        }
    }
}

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

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