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

如何在java中将数据写入txt文件?,java,path,filepath,filewriter,Java,Path,Filepath,Filewriter,我的班级: public class Test{ public static void writeSmth() { try { BufferedWriter out = new BufferedWriter( new FileWriter("one.txt")); out.write("content"); } catch (IOException e) {

我的班级:

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
当我尝试写入数据时,此文件不会发生任何变化。 我试过:

获取
java.io.FileNotFoundException
尝试:

还是什么都没发生

有什么问题吗?

您可以使用获取用户的主目录。对于文本输出,我更喜欢一个。接下来,您可以相对于该路径写入输出文件。我也会用一个。比如说

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

你试过从C:/folder1/folder2开始的整个绝对路径了吗?@yogidilip是的,我试过了,没有发生什么愚蠢的问题,但你真的调用了
writesth()
?无论出于何种原因,它都是静态的,但在相关注释中没有main。@secolive我在main中启动此方法:d在写入文件时,您不应该获得FileNotFoundException,除非路径不存在或您没有文件的写入权限。系统可能找不到该文件,而是在一个目录中创建文件,而不是OP认为的目录。@FredK我不认为这个解决方案是完全正确的。你怎么看?@KickButtowski注意到OP从不在
输出上调用
close
(缓冲)。@Elliott Frisch什么是“user.home”?@RuslanLomov用户的主目录或文件夹。它跨操作系统工作。
BufferedWriter out = new BufferedWriter(
                        new FileWriter("./one.txt"));
File file = new File(System.getProperty("user.home"), "one.txt");
try (PrintStream ps = new PrintStream(file)) {
    ps.println("content");
} catch (FileNotFoundException e) {
    e.printStackTrace();
}