【问题标题】:Buffered Writer .write not writing to file缓冲作家.write不写入文件
【发布时间】:2017-06-09 00:31:30
【问题描述】:

此代码未写入文件,我无法找到原因。

File file = DirectoryChooser.showDialog(fxcontroller.getPrimaryStage());
if (file != null) {
    BufferedWriter bw; 
    try {
        File defaultMusicPath = new File("../defaultMusicPath.txt");
        bw = new BufferedWriter(new FileWriter(defaultMusicPath,true));
        bw.write(file.getAbsolutePath());
        System.out.println("done");
        bw.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

此图显示 defaultMusicPath.txt 的位置

https://i.stack.imgur.com/8vxSO.png

如果您查看底部,此图像显示 file.getAbsolutePath() 不为空

按照别人所说的,我在这里做了一个最低限度的可验证示例。
我简化了它,但它仍然无法写入文件:

BufferedWriter bw;
File defaultMusicPath = new File("../defaultMusicPath.txt");
try {
    bw = new BufferedWriter(new FileWriter(defaultMusicPath,true));
    bw.write("it should write this");

    bw.flush();
    bw.close();
    System.out.println("done");
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

【问题讨论】:

  • 你得到了什么输出?
  • 因为你说输出什么都没有,但实际上根据你的图像,输出是done,所以通过添加System.out.println ("path:" + file.getAbsolutePath());来调试,看看你要写什么
  • 显示 defaultMusicPath.txt No 不是,你没有使用这个值。也许您正在查看错误的defaultMusicPath.txt 文件
  • 除非必要,否则请不要使用屏幕截图。不清楚您通过全屏捕获显示的内容
  • @Dylan 是的,有...一个在桌面的音乐文件夹中,另一个在您的 Eclipse 项目中

标签: java io bufferedwriter


【解决方案1】:

您正在选择一个放置文件的位置

File file = DirectoryChooser.showDialog(fxcontroller.getPrimaryStage());

您正在写入一个文件,该文件是 Eclipse 项目之外的一个文件夹(以防不清楚)

File defaultMusicPath = new File("../defaultMusicPath.txt");
bw = new BufferedWriter(new FileWriter(defaultMusicPath,true));

那么你将第一个 File 对象的路径正确地写入第二个 File 对象

bw.write(file.getAbsolutePath());

如果没有错误,那么您正在写入文件,因此您可能需要在编辑器中关闭并重新打开该文件。

如果要写入 Eclipse 项目,请删除相关的 ../

另外,我建议在 catch 之后在 finally 块中关闭作者。或者像这样使用 try-with-resources

File f = new File("defaultMusicPath.txt");
try (BufferedWriter bw = 
        Files.newBufferedWriter(Paths.get(f.toURI()), StandardOpenOption.APPEND); 
        PrintWriter out = new PrintWriter(bw)) {
    out.println("Hello, world!");
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

【讨论】:

  • 这是一个音乐播放器,目录选择器用于选择包含音乐的文件夹,而不是选择我想要的文本文件的位置。我不知道你是否感到困惑。
  • 蟋蟀 - 我认为我们正在输掉这场战斗
  • 我建议调试并从等式中删除目录选择器。这段代码应该可以工作
  • @DylanBurton:要理解 cricket_007 在这里所说的,您需要将问题简化为 minimal reproducible example。如果没有其他人可以重现该问题,那么没有人可以帮助您解决它。
  • 很高兴听到。我刚刚运行了这段代码,它有效,所以请随时接受答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-08
  • 1970-01-01
  • 2017-04-29
  • 2020-08-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多