我在写入 txt 文件时遇到问题。我收到 FileNotFound 异常,但我不知道为什么,因为该文件肯定存在。这是代码。
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.File;
public class Save
{
public static void main(String[] args)
{
File file = new File("C:/Users/Daniel/Desktop/Programs/Save Data Test/save.txt");
PrintWriter pw = new PrintWriter(file);
pw.println("Hello World");
pw.close();
}
}
最佳答案
在创建 PrintWriter
之前,您必须创建带有目录的实际文件
file.mkdirs();
file.createNewFile();
将它与适当的 try 和 catch block 一起使用看起来像这样......
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.File;
public class Save
{
public static void main(String[] args)
{
File file = new File("save.txt");
try {
file.mkdirs();
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
PrintWriter pw = new PrintWriter(file);
pw.println("Hello World");
pw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
关于Java PrintWriter 文件未找到,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29720934/