[英]FileOutputStream doesn't show FileNotFoundException
for FileOutputStream
, it will throw a FileNotFoundException
if the file doesn't exist, but it will create it if it can. 对于FileOutputStream
,如果文件不存在,它将抛出 FileNotFoundException
,但如果可以,它将创建 FileNotFoundException
。
I dont have a Sample.txt
in my project root 我的项目根目录中没有Sample.txt
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class Main {
public static void main(String[] args) {
try {
FileOutputStream s= new FileOutputStream("Sample.txt");
} catch (FileNotFoundException e) {
System.out.println("File not Found");
}
}
}
The problem is: 问题是:
Terminal
. 我无法从Terminal
看到“找不到文件”的输出。 How did it happen? 这是怎么发生的? Thank you 谢谢
You can set Sample.txt as a File first and check if it exists with .canWrite() 您可以先将Sample.txt设置为文件,然后使用.canWrite()检查它是否存在
You still have to put a try/catch around FileOutputStream, but it should never go in the catch block. 您仍然必须在FileOutputStream周围进行try / catch,但永远不要将其放入catch块中。
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class test {
public static void main(String[] args) {
File f = new File("Sample.txt");
if (!f.exists()) {
System.out.println("File not Found");
}
else {
try {
FileOutputStream s = new FileOutputStream(f);
} catch (FileNotFoundException e) {}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.