## 一、文件实例化的方法 * File path = new File(String dirPath); * File file = new File(String rootPath,String fileName); * File file = new File(File rootPath,String fileName); ## 二、创建目录 利用File对象的`mkdir()`和`mkdirs()`方法,文件路径有两种书写方法,可以用`/`作为分隔符,也可以用`\\`作为分割符,若系统无法确定可用`File.separator`(File类的常量)来分割,会自动识别系统类型进而添加分隔符。 路径可以为绝对路径和相对路径,相对路径开头为`./`表示运行项目的根目录。 #### 1、exists() 用来判断目录或文件是否存在,若存在返回true ```javascript // 引用文件目录 File path = new File("./class/src/test/java/TestFile/fileStudy/demo"); if (!path.exists()) { System.out.println("目录不存在"); } ``` #### 2、mkdir() 只能创建末尾最后一个文件夹,若中间路径不存在将会创建失败。 返回值为`boolean` ```javascript // 引用文件目录 File path = new File("./class/src/test/java/TestFile/fileStudy/demo"); if (!path.exists()) { System.out.println("目录不存在"); if (path.mkdir()) { System.out.println("目录创建成功"); } else { System.out.println("目录创建失败"); } } ``` #### 3、mkdirs() - 更常用 可以一次性补全给定路径上的所有未存在目录。 返回值为`boolean` ```javascript // 引用文件目录 File path = new File("./class/src/test/java/TestFile/fileStudy/demo"); if (!path.exists()) { System.out.println("目录不存在"); if (path.mkdirs()) { System.out.println("目录创建成功"); } else { System.out.println("目录创建失败"); } } ``` ## 三、文件操作 #### 1、创建文件 createNewFile() 返回值为`boolean`,创建成功返回true。 使用时会抛出`IOException`非运行时异常,所以必须进行异常捕获处理 ```javascript File file = new File("./class/src/test/java/TestFile/fileStudy", "test.txt")); if (!file.exists()) { System.out.println("文件不存在"); try { file.createNewFile(); System.out.println("文件创建成功"); } catch (IOException e) { System.out.println("文件创建失败"); e.printStackTrace(); } } ``` #### 2、删除文件 delete() 返回值为`boolean`,删除成功返回true, ```javascript File file = new File("./class/src/test/java/TestFile/fileStudy", "test.txt")); file.delete(); ``` #### 3、文件重命名 renameTo() 返回值为`boolean`,重命名成功返回true。 ```javascript File file = new File("./class/src/test/java/TestFile/fileStudy", "test.txt")); file.renameTo(new File("./class/src/test/java/TestFile/fileStudy", "test2.json")); ``` #### 4、文件路径获取 * 绝对路径获取 getAbsolutePath() 返回文件在系统目录内的绝对路径,包括文件名。 * 相对路径获取 getPath() 返回文件在File对象创建时的相对路径,若创建对象时使用的是绝对路径创建,那么返回值与getAbsolutePath()相同。 #### 5、获取目录内所有文件 listFiles() 返回值为`File[]`,内容为目录下所有文件的路径,不包含子目录。 ```javascript File[] fileList = new File(path).listFiles(); ``` **扩展:通过递归遍历文件夹内所有文件,包含子目录,并通过树结构输出。** ```javascript public static void printAllFiles(String path, int dirNums) { File[] fileList = new File(path).listFiles(); if (fileList != null) { for (File f : fileList) { for (int i = 1; i < dirNums; i++) { System.out.print("\t"); } if (dirNums != 0) { System.out.print("|"); System.out.print(dirNums+"—— "); } System.out.println(f.getName()); if (f.isDirectory()) { printAllFiles(f.getAbsolutePath(), dirNums + 1); } } } } ``` 用法:`printAllFiles("./", 0);` #### 6、其他常用文件操作方法 * isDirectory() 判断是否为目录 * isFile() 判断是否为文件 更多方法见:[[工具类] File类常见的方法](https://www.soki.me/archives/222.html) ## 四、文件数据读写 #### 1、流的分类 | **分类维度** | **类型** | **关键特点** | **典型实现类** | | ------------ | ---------------- | ----------------------- | ------------------------------------- | | 数据单位 | 字节流 | 操作字节(8位) | `FileInputStream`/`FileOutputStream` | | | 字符流 | 操作字符(16位Unicode) | `FileReader`/`FileWriter` | | 功能角色 | 节点流(低级流) | 直接连接数据源 | `FileReader`, `ByteArrayOutputStream` | | | 缓冲流(高级流) | 增强功能(缓冲/转换等) | `BufferedReader`, `ObjectInputStream` | | 方向 | 输入流 | 从源读取数据 | `InputStream`, `Reader` | | | 输出流 | 向目标写入数据 | `OutputStream`, `Writer` | | 阻塞机制 | 阻塞流 | 同步阻塞I/O | `java.io` 中所有流 | | | 非阻塞流 | 基于NIO的异步I/O | `FileChannel`, `ByteBuffer` | #### 2、字符流的读操作 “低级流”:`FileReader` “高级流”:`BufferedReader` 高级流需要在低级流的基础上进行操作,高级流效率更高。 IO操作必须处理`IOException`异常,所以必须在try块中进行操作。 ```javascript File file = new File("./class/src/test/java/TestFile/fileStudy", "test.txt")); FileReader fr = null; BufferedReader br = null; try { fr = new FileReader(file); br = new BufferedReader(fr); String str; // 遍历文本文件,把所有内容都输出 do { str = br.readLine(); if (str != null) System.out.println(str); } while (str != null); } catch (IOException e) { System.out.println(e.getMessage()); } finally { // 读完后把流关闭 try { if (br != null) { br.close(); } if (fr != null) { fr.close(); } } catch (IOException e) { System.out.println(e.getMessage()); } } ``` #### 3、字符流的写操作 “低级流”:`FileWriter` “高级流”:`BufferedWriter` 高级流需要在低级流的基础上进行操作,高级流效率更高。 IO操作必须处理`IOException`异常,所以必须在try块中进行操作。 ```javascript File file = new File("./class/src/test/java/TestFile/fileStudy", "test.txt")); FileWriter fw; BufferedWriter bw; try { fw = new FileWriter(file, false); // append参数,意为是否续写,默认为false bw = new BufferedWriter(fw); for (int i = 0; i < 16; i++) { bw.write(getRandomStrings(16)); bw.newLine(); } bw.close(); fw.close(); } catch (IOException e) { System.out.println(e.getMessage()); } ``` **扩展:循环中的随机取任意长度字符串** ``` public static String getRandomStrings(int length) throws IndexOutOfBoundsException { if (length < 0) throw new IndexOutOfBoundsException("长度不能为负数"); Random r = new Random(); StringBuilder sb = new StringBuilder(); char[] arr = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; for (int i = 0; i < length; i++) { sb.append(arr[r.nextInt(arr.length)]); } return sb.toString(); } ``` #### 4、字符流的拷贝 利用读写操作进行文件拷贝 ```javascript File path = new File("./class/src/test/java/TestFile/fileStudy"); File file1 = new File(path, "test.txt"); File file2 = new File(path, "test2.txt"); FileReader fr = null; BufferedReader br = null; FileWriter fw = null; BufferedWriter bw = null; try { if (!file2.exists()) { if (file2.createNewFile()) System.out.println("test2.txt文件创建成功"); } fr = new FileReader(file1); br = new BufferedReader(fr); fw = new FileWriter(file2,true); bw = new BufferedWriter(fw); String str; do { str = br.readLine(); if (str != null) { bw.write(str); bw.newLine(); } } while (str != null); } catch (IOException e) { System.out.println(e.getMessage()); } finally { try {// 关闭流的时候需要先关闭高级流再关闭低级流,否则回出现重复关闭的异常 if (br != null) { br.close(); } if (fr != null) { fr.close(); } if (bw != null) { bw.close(); } if (fw != null) { fw.close(); } } catch (IOException e) { System.out.println(e.getMessage()); } } ``` #### 5、字节流的拷贝 “低级流”:`FileInputStream`,`FileOutputStream` “高级流”:`BufferedInputStream`,`BufferedOutputStream` ```javascript File path = new File("./class/src/test/java/TestFile/fileStudy"); File file1 = new File(path, "1.png"); File file2 = new File(path, "2.png"); FileInputStream in = null; BufferedInputStream bin = null; FileOutputStream out = null; BufferedOutputStream bout = null; try { if (!file2.exists()) { if (file2.createNewFile()) System.out.println("2.png文件创建成功"); } in = new FileInputStream(file1); bin = new BufferedInputStream(in); out = new FileOutputStream(file2); bout = new BufferedOutputStream(out); int dataLength; do { dataLength = bin.read(); if (dataLength != -1) { bout.write(dataLength); } } while (dataLength != -1); } catch (IOException e) { System.out.println(e.getMessage()); } finally { try { if (bin != null) { bin.close(); } if (in != null) { in.close(); } if (bout != null) { bout.close(); } if (out != null) { out.close(); } } catch (IOException e) { System.out.println(e.getMessage()); } } ``` Loading... ## 一、文件实例化的方法 * File path = new File(String dirPath); * File file = new File(String rootPath,String fileName); * File file = new File(File rootPath,String fileName); ## 二、创建目录 利用File对象的`mkdir()`和`mkdirs()`方法,文件路径有两种书写方法,可以用`/`作为分隔符,也可以用`\\`作为分割符,若系统无法确定可用`File.separator`(File类的常量)来分割,会自动识别系统类型进而添加分隔符。 路径可以为绝对路径和相对路径,相对路径开头为`./`表示运行项目的根目录。 #### 1、exists() 用来判断目录或文件是否存在,若存在返回true ```javascript // 引用文件目录 File path = new File("./class/src/test/java/TestFile/fileStudy/demo"); if (!path.exists()) { System.out.println("目录不存在"); } ``` #### 2、mkdir() 只能创建末尾最后一个文件夹,若中间路径不存在将会创建失败。 返回值为`boolean` ```javascript // 引用文件目录 File path = new File("./class/src/test/java/TestFile/fileStudy/demo"); if (!path.exists()) { System.out.println("目录不存在"); if (path.mkdir()) { System.out.println("目录创建成功"); } else { System.out.println("目录创建失败"); } } ``` #### 3、mkdirs() - 更常用 可以一次性补全给定路径上的所有未存在目录。 返回值为`boolean` ```javascript // 引用文件目录 File path = new File("./class/src/test/java/TestFile/fileStudy/demo"); if (!path.exists()) { System.out.println("目录不存在"); if (path.mkdirs()) { System.out.println("目录创建成功"); } else { System.out.println("目录创建失败"); } } ``` ## 三、文件操作 #### 1、创建文件 createNewFile() 返回值为`boolean`,创建成功返回true。 使用时会抛出`IOException`非运行时异常,所以必须进行异常捕获处理 ```javascript File file = new File("./class/src/test/java/TestFile/fileStudy", "test.txt")); if (!file.exists()) { System.out.println("文件不存在"); try { file.createNewFile(); System.out.println("文件创建成功"); } catch (IOException e) { System.out.println("文件创建失败"); e.printStackTrace(); } } ``` #### 2、删除文件 delete() 返回值为`boolean`,删除成功返回true, ```javascript File file = new File("./class/src/test/java/TestFile/fileStudy", "test.txt")); file.delete(); ``` #### 3、文件重命名 renameTo() 返回值为`boolean`,重命名成功返回true。 ```javascript File file = new File("./class/src/test/java/TestFile/fileStudy", "test.txt")); file.renameTo(new File("./class/src/test/java/TestFile/fileStudy", "test2.json")); ``` #### 4、文件路径获取 * 绝对路径获取 getAbsolutePath() 返回文件在系统目录内的绝对路径,包括文件名。 * 相对路径获取 getPath() 返回文件在File对象创建时的相对路径,若创建对象时使用的是绝对路径创建,那么返回值与getAbsolutePath()相同。 #### 5、获取目录内所有文件 listFiles() 返回值为`File[]`,内容为目录下所有文件的路径,不包含子目录。 ```javascript File[] fileList = new File(path).listFiles(); ``` **扩展:通过递归遍历文件夹内所有文件,包含子目录,并通过树结构输出。** ```javascript public static void printAllFiles(String path, int dirNums) { File[] fileList = new File(path).listFiles(); if (fileList != null) { for (File f : fileList) { for (int i = 1; i < dirNums; i++) { System.out.print("\t"); } if (dirNums != 0) { System.out.print("|"); System.out.print(dirNums+"—— "); } System.out.println(f.getName()); if (f.isDirectory()) { printAllFiles(f.getAbsolutePath(), dirNums + 1); } } } } ``` 用法:`printAllFiles("./", 0);` #### 6、其他常用文件操作方法 * isDirectory() 判断是否为目录 * isFile() 判断是否为文件 更多方法见:[[工具类] File类常见的方法](https://www.soki.me/archives/222.html) ## 四、文件数据读写 #### 1、流的分类 | **分类维度** | **类型** | **关键特点** | **典型实现类** | | ------------ | ---------------- | ----------------------- | ------------------------------------- | | 数据单位 | 字节流 | 操作字节(8位) | `FileInputStream`/`FileOutputStream` | | | 字符流 | 操作字符(16位Unicode) | `FileReader`/`FileWriter` | | 功能角色 | 节点流(低级流) | 直接连接数据源 | `FileReader`, `ByteArrayOutputStream` | | | 缓冲流(高级流) | 增强功能(缓冲/转换等) | `BufferedReader`, `ObjectInputStream` | | 方向 | 输入流 | 从源读取数据 | `InputStream`, `Reader` | | | 输出流 | 向目标写入数据 | `OutputStream`, `Writer` | | 阻塞机制 | 阻塞流 | 同步阻塞I/O | `java.io` 中所有流 | | | 非阻塞流 | 基于NIO的异步I/O | `FileChannel`, `ByteBuffer` | #### 2、字符流的读操作 “低级流”:`FileReader` “高级流”:`BufferedReader` 高级流需要在低级流的基础上进行操作,高级流效率更高。 IO操作必须处理`IOException`异常,所以必须在try块中进行操作。 ```javascript File file = new File("./class/src/test/java/TestFile/fileStudy", "test.txt")); FileReader fr = null; BufferedReader br = null; try { fr = new FileReader(file); br = new BufferedReader(fr); String str; // 遍历文本文件,把所有内容都输出 do { str = br.readLine(); if (str != null) System.out.println(str); } while (str != null); } catch (IOException e) { System.out.println(e.getMessage()); } finally { // 读完后把流关闭 try { if (br != null) { br.close(); } if (fr != null) { fr.close(); } } catch (IOException e) { System.out.println(e.getMessage()); } } ``` #### 3、字符流的写操作 “低级流”:`FileWriter` “高级流”:`BufferedWriter` 高级流需要在低级流的基础上进行操作,高级流效率更高。 IO操作必须处理`IOException`异常,所以必须在try块中进行操作。 ```javascript File file = new File("./class/src/test/java/TestFile/fileStudy", "test.txt")); FileWriter fw; BufferedWriter bw; try { fw = new FileWriter(file, false); // append参数,意为是否续写,默认为false bw = new BufferedWriter(fw); for (int i = 0; i < 16; i++) { bw.write(getRandomStrings(16)); bw.newLine(); } bw.close(); fw.close(); } catch (IOException e) { System.out.println(e.getMessage()); } ``` **扩展:循环中的随机取任意长度字符串** ``` public static String getRandomStrings(int length) throws IndexOutOfBoundsException { if (length < 0) throw new IndexOutOfBoundsException("长度不能为负数"); Random r = new Random(); StringBuilder sb = new StringBuilder(); char[] arr = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; for (int i = 0; i < length; i++) { sb.append(arr[r.nextInt(arr.length)]); } return sb.toString(); } ``` #### 4、字符流的拷贝 利用读写操作进行文件拷贝 ```javascript File path = new File("./class/src/test/java/TestFile/fileStudy"); File file1 = new File(path, "test.txt"); File file2 = new File(path, "test2.txt"); FileReader fr = null; BufferedReader br = null; FileWriter fw = null; BufferedWriter bw = null; try { if (!file2.exists()) { if (file2.createNewFile()) System.out.println("test2.txt文件创建成功"); } fr = new FileReader(file1); br = new BufferedReader(fr); fw = new FileWriter(file2,true); bw = new BufferedWriter(fw); String str; do { str = br.readLine(); if (str != null) { bw.write(str); bw.newLine(); } } while (str != null); } catch (IOException e) { System.out.println(e.getMessage()); } finally { try {// 关闭流的时候需要先关闭高级流再关闭低级流,否则回出现重复关闭的异常 if (br != null) { br.close(); } if (fr != null) { fr.close(); } if (bw != null) { bw.close(); } if (fw != null) { fw.close(); } } catch (IOException e) { System.out.println(e.getMessage()); } } ``` #### 5、字节流的拷贝 “低级流”:`FileInputStream`,`FileOutputStream` “高级流”:`BufferedInputStream`,`BufferedOutputStream` ```javascript File path = new File("./class/src/test/java/TestFile/fileStudy"); File file1 = new File(path, "1.png"); File file2 = new File(path, "2.png"); FileInputStream in = null; BufferedInputStream bin = null; FileOutputStream out = null; BufferedOutputStream bout = null; try { if (!file2.exists()) { if (file2.createNewFile()) System.out.println("2.png文件创建成功"); } in = new FileInputStream(file1); bin = new BufferedInputStream(in); out = new FileOutputStream(file2); bout = new BufferedOutputStream(out); int dataLength; do { dataLength = bin.read(); if (dataLength != -1) { bout.write(dataLength); } } while (dataLength != -1); } catch (IOException e) { System.out.println(e.getMessage()); } finally { try { if (bin != null) { bin.close(); } if (in != null) { in.close(); } if (bout != null) { bout.close(); } if (out != null) { out.close(); } } catch (IOException e) { System.out.println(e.getMessage()); } } ``` 最后修改:2025 年 10 月 13 日 © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 👆请简单粗暴地爱我。