如何将数据写入java中的txt文件?

How to write data to txt file in java?

我的class:

public class Test{
public static void writeSmth() {
        try {
            BufferedWriter out = new BufferedWriter(
                    new FileWriter("one.txt"));
            out.write("content");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

txt 文件的位置:

/ProjectName/one.txt

当我尝试写入数据时,此文件没有任何反应。 我试过了:

BufferedWriter out = new BufferedWriter(
                        new FileWriter("/ProjectName/one.txt"));

得到java.io.FileNotFoundException 尝试过:

BufferedWriter out = new BufferedWriter(
                        new FileWriter("./one.txt"));

仍然没有任何反应。

有什么问题?

您可以使用 System.getProperty(String) to get the user's home directory. For text output I'd prefer a PrintStream. Next, you can write to your output file relative to that path. I'd also use a try-with-resources Statement。有点像,

File file = new File(System.getProperty("user.home"), "one.txt");
try (PrintStream ps = new PrintStream(file)) {
    ps.println("content");
} catch (FileNotFoundException e) {
    e.printStackTrace();
}