JAVA 文件的基础操作

9 min read
public class Main {

  public static void main(String[] args) throws IOException {
    File file = new File("/Users/pan/Desktop/logs/tmp.txt");
    
    boolean isFile = file.isFile();
    System.out.println("是否是文件类型:" + isFile);
  
    boolean exists = file.exists();
    System.out.println("文件是否存在:" + exists);
    
    if (!exists){
      boolean newFile = file.createNewFile();
      System.out.println("是否创建成功:" +newFile);
    }else {
      boolean delete = file.delete();
      System.out.println("是否删除成功:" + delete);
    }
  }

}
  • 系统分隔符 File.separator

  • 相对路径和绝对路径,如果直接提供"data.txt" 这样的路径,就是在当前执行文件同目录下

  • 在linux下文件夹也是一种特殊的文件

  • 可以获取的基础的元信息包括:文件名\绝对路径\相对路径\最后修改时间\创建时间\文件大小\文件权限\是否是隐藏文件等