一、操作文件:
Path和Files类封装了用户机器上处理文件系统所需要的所有功能。
1.Path类
方法:
- 1.//获取文件路径
- Paths.get(“路径”)
- Paths.get(“/home”,“my”)
/home/my
通过上述方法,获取文件路径后,可通过Path类的对象,调用下边的一些方法,
-
path.getFileName()
-
path.getParent()
-
path.getRoot()
-
path.getFileSystem()
2. Files 类
方法:
- 方法:
-
Files.readAllBytes(path) //全部读入文件内容
-
Files.readAllLines(path) //一行一行读取
-
Files.exists(path) //判断目录或者文件是否存在
-
Files.createDirectory(path)
-
Files.createFile(path)
-
Files.deleteIfExists(path)
-
Files.delete() //没有判断直接删除
3.上述方法的代码测试:
/**
* @Author Janson
* @Date 2022/4/18 10:12
* @Version 1.0
*/
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
/**
* Paths 类
* 方法:
* Paths.get("路径")
* Paths.get("/home","my")
* /home/my
* path.getFileName()
* path.getParent()
* path.getRoot()
* path.getFileSystem()
* Files 类
* 方法:
* Files.readAllBytes(path)
* Files.readAllLines(path)
* Files.exists(path)
* Files.createDirectory(path)
* Files.createFile(path)
* Files.deleteIfExists(path)
* Files.delete() //没有判断直接删除
*
*/
public class NioPrac {
public static void main(String[] args) throws IOException {
//获取当前用户的绝对路径(相对路径以上的路径)
String userDir = System.getProperty("user.dir");
System.out.println(userDir);
Path path = Paths.get(userDir, "testData/longWord");
System.out.println(path);
//Paths 类中的方法测试
System.out.println("1 " + path.getFileName());
System.out.println("2 " + path.getParent());
System.out.println("3 " + path.getRoot());
System.out.println("4 " + path.getFileSystem());
List<String> strings = Files.readAllLines(path);
strings.forEach(string-> System.out.println("stringArrays======>" + string));
String stringArray = new String(Files.readAllBytes(path));
//for (s stringByte : stringArrays) {
// System.out.println("stringByte ======> " + stringByte);
//}
System.out.println("stringArray--------=====>" + stringArray);
//在创建目录前进行判断,是否存在该目录
boolean exists = Files.exists(Paths.get("O:\\code\\BeforeSleeping30m\\testData\\my2"));
if (!exists) {
Path directory = Files.createDirectory(Paths.get("O:\\code\\BeforeSleeping30m\\testData\\my2"));
System.out.println("directory====>"+ directory);
}
//创建文件,创建前先判断是否存在文件,若存在,则不进行创建
boolean existsFile = Files.exists(Paths.get("O:\\code\\BeforeSleeping30m\\testData\\my\\my2.txt"));
if (!existsFile) {
Path file = Files.createFile(Paths.get("O:\\code\\BeforeSleeping30m\\testData\\my\\my2.txt"));
System.out.println("新创建的file的路径:" + file);
}
boolean deleteIfExists = Files.deleteIfExists(Paths.get("O:\\code\\BeforeSleeping30m\\testData\\my\\my2.txt"));
if (deleteIfExists){
System.out.println("删除成功!");
}
}
}