Java文件操作的简单示例
使用原生库
创建空白文件
package com.company;
import java.io.File;
import java.io.IOException;public class Main {public static void main(String[] args) {File f = new File("newfile.txt");try {boolean flag = f.createNewFile();System.out.println("创建状态="+flag);} catch (IOException e) {e.printStackTrace();}System.out.println("over");}
}
关于createNewFile
方法的说明:
- 如果文件不存在,则创建。创建成功后返回true。
- 如果文件已经存在,则不会重复创建或覆盖,此时返回false。
创建文件并写入内容/重新覆盖内容
package com.company;
import java.io.FileWriter;
import java.io.IOException;public class Main {public static void main(String[] args) {try {FileWriter writer = new FileWriter("newfile2.txt");writer.write("hello world!");writer.close();} catch (IOException e) {e.printStackTrace();}System.out.println("over");}
}
关于FileWriter :
- 如果文件不存在,则会创建一个空白文件,并向里面写入内容。
- 如果文件已存在,则清空文件里面内容,并重新写入内容(也就是覆盖文件内容了)。
- 必须调用close方法,不然只会创建一个空白文件(文件存在则会清空里面内容),而文本内容无法写入到文件。
- 如果不调用close方法,那么在程序停止前该文件则会被占用,导致无法删除文件。
逐行读取文件内容
File f = new File("newfile.txt");try {Scanner scanner = new Scanner(f);while(scanner.hasNextLine()){String line = scanner.nextLine();System.out.println(line);}scanner.close();} catch (FileNotFoundException e) {e.printStackTrace();}
如果不close,同样会占用文件,无法及时释放资源。
读取文件的基本信息
File f = new File("newfile.txt");if(f.exists()){System.out.println("Name = " + f.getName());System.out.println("AbsolutePath = " + f.getAbsolutePath());System.out.println("Path = " + f.getPath());System.out.println("canWrite = " + f.canWrite());System.out.println("canRead = " + f.canRead());System.out.println("The length, in bytes = " + f.length());}
例如输出:
Name = newfile.txt
AbsolutePath = D:\test\newfile.txt
Path = newfile.txt
canWrite = true
canRead = true
The length, in bytes = 15
删除单个文件
File f = new File("newfile.txt");if(f.delete()){System.out.println("删除成功:" + f.getAbsolutePath());}else{System.out.println("删除失败:" + f.getAbsolutePath());}
删除空白文件夹
空白文件夹名为Tmp。
File f = new File("Tmp");if(f.delete()){System.out.println("删除文件夹成功:" + f.getAbsolutePath());}else{System.out.println("删除文件夹失败:" + f.getAbsolutePath());}
如果文件夹不存在或者文件夹非空,则删除失败。
使用hutool
使用hutool中的FileUtil
工具类。
参考文档
参考API:https://plus.hutool.cn/apidocs/
删除文件夹
删除文件夹时不会判断文件夹是否为空,如果不空则递归删除子文件或文件夹。
del中也可以输入文件夹或文件路径,但试了似乎只能绝对路径,相对路径没试成功。
File f = new File("tmp");if(f.exists()){boolean flag = FileUtil.del(f);System.out.println(flag);}