直接上代码:
package test;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;
public class Test {
public static void main(String[] args) throws IOException {
/**
* File和Path都可以代表文件或目录
*/
//**********************Path****************************
//创建Path对象的两种方式,代表一个目录或文件
Path p1 = Paths.get("C:\\Users\\86150\\Desktop\\hello.txt");
System.out.println(p1);
Path p2 = Path.of("C:\\Users\\86150\\Desktop\\hello.txt");
System.out.println(p2);
//把Path对象转为File对象
File file = p1.toFile();
//获取父路径
Path parentPath = p1.getParent();
System.out.println(parentPath);
//获取文件名/目录名
Path itself = p1.getFileName();
System.out.println(itself.toString());
//***********************Files工具类**************************
//一次性读取文件中所有字节
byte[] bytes = Files.readAllBytes(p1);
System.out.println(new String(bytes, "utf-8"));
//读取字符流
String str = Files.readString(p1);
System.out.println(str);
//按行读取,把每一行当成一个元素组成字符串List
List<String> list = Files.readAllLines(p1);
//以字节为单位写入数据,第三个参数是选项
byte[] bytes1 = "woshiliqighao".getBytes();
Path path1 = Path.of("C:\\Users\\86150\\Desktop\\hello1.txt");
Files.write(path1, bytes1, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
//把字符串写入文件
String str1 = "hhaha";
Path path2 = Path.of("C:\\Users\\86150\\Desktop\\hello2.txt");
Files.writeString(path2, str1, StandardOpenOption.CREATE);
//把List<String>写到文件;略;
//Files还有三个方法与File类相对应,分别是createFile() createDirectory() createDirectories()
//**********************File类****************************
//文件
File file1 = new File("C:\\Users\\86150\\Desktop\\hello3.txt");
//在磁盘上创建新文件
file1.createNewFile();
//删除文件
file1.delete();
System.out.println(file1.isFile());
System.out.println(file1.isDirectory());
System.out.println(file1.exists());
//目录
File file2 = new File("C:\\Users\\86150\\Desktop\\hello\\haha");
System.out.println(file2.mkdir());
System.out.println(file2.mkdirs());//mkdirs会创建所需中间目录
}
}