【问题标题】:PrintWriter not writing to .java filePrintWriter 不写入 .java 文件
【发布时间】:2015-03-21 00:55:41
【问题描述】:

代码编译并且没有错误被抛出。但是,文本没有打印到我的 .java 文件中。我尝试打印到 .txt 文件,但这也不起作用。我要打印到的文件与我的 Main 类位于同一目录中。我知道 PrintWriter 不工作的两个最常见原因是没有关闭 PrintWriter 并且没有正确的路径。我认为这两个都不是问题,但我可能忽略了一些东西。任何帮助深表感谢!

这是我的代码,省略了不相关的部分:

public class Main {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() { 
                Gui gui = new Gui();
                gui.createAndShowGUI();
                gui.setVisible(true);
            }
        });

        //System.out.println(new File(".").getAbsolutePath());
        File file = new File("C:\\Users\\Me\\Desktop\\Basket.java");
        PrintWriter pw = null;

        try {
            pw = new PrintWriter(file);
            pw.println("hello there");
            pw.flush();// tried with and without flushing;
            // System.out.println(pw.checkError());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (pw != null) {
                pw.close();
            }
        }
    }
}

【问题讨论】:

  • 没有例外?执行后文件是否不存在?
  • 尝试检查文件是否存在。使用这样的东西:if (!myFile.exists()) { myFile.createNewFile(); }
  • 您写入文件的代码确实按预期工作(我自己运行了它),但我不确定前面的代码在做什么...您是否逐步查看了您的代码你是否真的到达了文件写入部分?也许你卡在 GUI 初始化部分,而文件写入部分没有被执行?

标签: java printwriter file-writing


【解决方案1】:

问题是我需要在 Eclipse 中手动刷新我的项目目录视图。快捷键:F5。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-22
    • 1970-01-01
    相关资源
    最近更新 更多