代码编译并且没有错误被抛出。但是,文本没有打印到我的 .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();
}
}
}
}