IO - File

IO - File

创建

  1. new File(String filePath)

    String filePath = "D:\\news1.txt";
    File file = new File(filePath); // 此时尚未将文件写入硬盘
    try {
        file.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
    }
    
  2. new File(File parent, String child)

    File parent = new File("D:\\");
    File file = new File(parent, "news2.txt"); // 此时尚未将文件写入硬盘
    try {
        file.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
    }
    
  3. new File(String parent, String Child)

    String parent = "D:\\";
    String child = "news3.txt";
    File file = new File(parent, child);
    try {
        file.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
    }
    

常用方法

测试用文件

D:\\\news1.txt UTF-8

你好world

测试代码

File file = new File("D:\\news1.txt");
// FileName
String fileName = file.getName();// news1.txt
// AbsPath
String fileAbsolutePath = file.getAbsolutePath(); // D:\
// Parent
String fileParent = file.getParent();// D:\
// Byte
long filesLength = file.length();// 11 -> 汉字 3B/字 + 英文 1B/char 
// Exist? 目录或者文件
boolean exists = file.exists();// true
// isFile
boolean isFile = file.isFile();// true
// isPath
boolean isDirectory = file.isDirectory();// false

删除文件

public boolean delete()

判断目录存在

public boolean exists()

创建目录

public boolean mkdir() // 创建单级目录

public boolean mkdirs() // 创建多级目录

posted @ 2022-07-20 11:04  jentreywang  阅读(20)  评论(0编辑  收藏  举报