我在写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();
}
}发布于 2015-04-18 18:39:20
在创建PrintWriter put之前,必须创建包含其目录的实际文件
file.mkdirs();
file.createNewFile();用这个和适当的尝试和捕捉块会看起来像这样.
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();
}
}
}发布于 2015-04-18 20:17:24
仅仅因为您知道文件在那里,并不意味着您的代码在尝试处理之前不应该检查它的存在。
至于您的FileNotFound异常,如果IDE检测到可能发生异常,一些Java会强迫您编写try/catch块。
例如,NetBeans代码甚至不会编译:

您必须编写一个try/catch块来处理潜在的异常
public static void main(String[] args) {
File file = new File("C:/Users/Daniel/Desktop/Programs/Save Data Test/save.txt");
if (file.exists()) {
try {
PrintWriter pw = new PrintWriter(file);
pw.println("Hello World");
pw.close();
} catch (FileNotFoundException fnfe){
System.out.println(fnfe);
}
}
}发布于 2022-06-16 13:26:47
转这个:public static void main(String[] args)
这方面:
public static void main(String[] args) throws FileNotFoundException一切都会好起来的。
https://stackoverflow.com/questions/29720934
复制相似问题