您好,我是 Java 初学者,请用简单的术语解释一下。我正在制作 FileHandling.java 文件,我尝试在其中读取文件并写入其他文件,但在读写操作后我想关闭这两个文件但我的主要问题是我如何知道是否有这样的文件。根据文件是否存在我想关闭我的文件。这是我的java代码:
import java.io.*;
public class FileHandling {
public static void main(String args[])
{
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}
catch(IOException e)
{
System.out.println("Here some IO problem :"+e);
}
finally {
System.out.println("Finally Block executed");
if(in.exists()){in.close();System.out.println("in file closed");}
else{System.out.println("in file doesn't exist to close operation");}
if(out.exists()){out.close();System.out.println("out file closed");}
else{System.out.println("out file doesn't exist to close operation");}
}
}
}
最佳答案
你可以检查它们是否为空
finally {
System.out.println("Finally Block executed");
if(in != null ){
in.close();
System.out.println("in file closed");
}
else{
System.out.println("in file doesn't exist to close operation");
}
if(out != null){
out.close();
System.out.println("out file closed");}
else{
System.out.println("out file doesn't exist to close operation");}
}
}
或者您可以使用 try with resources如果使用 Java 7 或更高版本。
try (in = new FileInputStream("input.txt")) {
try (out = new FileOutputStream("output.txt")) {
}
}
一旦方法完成,这将自动关闭资源,而无需使用 finally block 。
关于java - 如何检查文件是否存在,如果存在,那么我想在 java 的 finally block 中关闭它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37961029/