从java7开始为操作文件提供了很便利的类Files
读取文件内容 返回byte[]
byte[] bytes = Files.readAllBytes(Path.of("src/b.txt"));
读取文件内容返回为String
Files.readString(Path.of("src/b.txt"));
Files.readString(Path.of("src/b.txt"),charset);//设置读取编码
读取文件每一行 返回list
List<String> list = Files.readAllLines(Path.of("src/b.txt"));
System.out.println(list);
写操作也很容易
写入字节数组
byte[] bytes=..
Files.write(Path.of("src/a.txt"),bytes);
写入字符串
Files.writeString(Path.of("src/a.txt"),"content",StandardCharsets.UTF_8);
按行写入
List<String> list=...
Files.write(Path.of("src/a.txt"),list);
复制文件
Path copy = Files.copy(Path.of("src\\abc.txt"), Path.of("src\\aa.txt"));//【注】第二个貌似要求文件不存在
long l = Files.copy(Path.of("src\\abc.txt"), new FileOutputStream("src/a.txt"));//返回字节数
long l = Files.copy(new FileInputStream("src/abc.txt"),Path.of("src/a.txt"));
文件大小
long size = Files.size(Path.of("src/a.txt"));
System.out.println(size);