Files的使用,一些常用的方法
package com.it.learn_file;
import org.junit.Test;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
/**
* @BelongsProject: learn_java
* @BelongsPackage: com.it.learn_file
* @CreateTime: 2023/2/10 13:56
* @author:
* @version: 1.0
*/
public class FileMethodUse {
@Test
public void Test(){
//自定义一个文件路径
String filePath = "d://test.txt";
//将String转化为path
Path path = Paths.get(filePath);
System.out.println("文件是否存在?"+Files.exists(path));
//创建文件
try {
if (Files.exists(path)){
//删除文件
Files.delete(path);
}
Files.createFile(path);
String word = "abc";
//将word的值写入文件
Files.write(path,word.getBytes());
//读出文件
List<String> strings = Files.readAllLines(path);
System.out.println("写入的文件内容为:"+strings.stream().collect(Collectors.joining()));
//查看文件个数
System.out.println("文件个数?"+ Files.size(path));
}catch (Exception e){
e.printStackTrace();
}
System.out.println("文件是否存在?"+Files.exists(path));
}
@Test
public void Test2(){
Path path = Paths.get("d://ccc");
//创建一个文件夹
try {
Files.createDirectories(path);
System.out.println("文件是否存在?"+Files.exists(path));
//查看文件个数
System.out.println("文件个数?"+ Files.size(path));
Files.delete(path);
System.out.println("文件是否存在?"+Files.exists(path));
}catch (Exception e){
e.printStackTrace();
}
}
}