用Java编写文本文件的最简单方法是什么?

2022-08-31 22:17:04

我想知道用Java编写文本文件的最简单(也是最简单的)方法是什么。请简单一点,因为我是初学者:D

我在网上搜索并找到了这个代码,但我理解其中的50%。

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

public class WriteToFileExample {
public static void main(String[] args) {
    try {

        String content = "This is the content to write into file";

        File file = new  File("C:/Users/Geroge/SkyDrive/Documents/inputFile.txt");

        // if file doesnt exists, then create it
        if (!file.exists()) {
            file.createNewFile();
        }

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

        System.out.println("Done");

    } catch (IOException e) {
        e.printStackTrace();
    }
}

}


答案 1

在 Java 7 及更高版本中,使用 Files 的一个 liner:

String text = "Text to save to file";
Files.write(Paths.get("./fileName.txt"), text.getBytes());

答案 2

您可以通过使用新的 .JAVA 7File API

代码示例:'

public class FileWriter7 {
    public static void main(String[] args) throws IOException {
        List<String> lines = Arrays.asList(new String[] { "This is the content to write into file" });
        String filepath = "C:/Users/Geroge/SkyDrive/Documents/inputFile.txt";
        writeSmallTextFile(lines, filepath);
    }

    private static void writeSmallTextFile(List<String> aLines, String aFileName) throws IOException {
        Path path = Paths.get(aFileName);
        Files.write(path, aLines, StandardCharsets.UTF_8);
    }
}

`