【问题标题】:How to write data to txt file in java?如何在java中将数据写入txt文件?
【发布时间】:2015-10-21 20:12:30
【问题描述】:

我的班级:

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

仍然没有任何反应。

有什么问题?

【问题讨论】:

  • 您是否尝试过从 C:/folder1/folder2 开始的整个绝对路径?
  • @yogidilip 是的,我试过了,没有任何反应
  • 愚蠢的问题,但你真的在调用writeSmth()吗?无论出于何种原因,它都是静态的,但在相关说明中没有 main。
  • @secolive 我在 main 中启动此方法:D
  • 写入文件时不应出现 FileNotFoundException,除非路径不存在或您没有文件的写入权限

标签: java path filepath filewriter


【解决方案1】:

您可以使用System.getProperty(String) 获取用户的主目录。对于文本输出,我更喜欢PrintStream。接下来,您可以写入相对于该路径的输出文件。我也会使用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();
}

【讨论】:

  • 可能不是系统找不到该文件,而是该文件是在OP认为的目录之外的目录中创建的。
  • @FredK 我不认为这个解决方案是完全证明的。你怎么看?
  • @KickButtowski 请注意,OP 永远不会在 out 上调用 close(这是缓冲)。
  • @Elliott Frisch 什么是“user.home”?
  • @RuslanLomov 用户的主目录或文件夹。它可以跨操作系统运行。
猜你喜欢
  • 1970-01-01
  • 2022-09-27
  • 1970-01-01
  • 1970-01-01
  • 2014-09-02
  • 2013-10-04
  • 1970-01-01
  • 1970-01-01
  • 2016-09-01
相关资源
最近更新 更多