java - 如何检查文件是否存在,如果存在,那么我想在 java 的 finally block 中关闭它?

标签 java

您好,我是 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/

相关文章:

java - Android 中带有多个按钮的自定义圆圈

java - 转换类以调用子类中的方法

java - 我不断收到 NullPointerException 错误,我已经处理了几个小时但找不到修复方法

java - 图像上传在 localhost 上工作正常,但在 jsp 中的服务器中工作不正常

java - 使用 Groovy 脚本约束进行结构搜索和替换

java - 正斜杠在 Path.resolve 中可以跨平台工作吗?

java - ArrayList 中的对象有引用吗?

java - mybatis 设置 mysql 在 tomcat 服务器上超时

java - 为什么我的 getTimeZone().getDisplayName 报告错误的偏移量?

java - Lunar Lander 中的 Android 垃圾收集