java文件操作之Path,Paths,Files

作者:wbb 时间:2023-11-19 15:34:34 

Java7中文件IO发生了很大的变化,专门引入了很多新的类:

import java.nio.file.DirectoryStream;

import java.nio.file.FileSystem;

import java.nio.file.FileSystems;

import java.nio.file.Files;

import java.nio.file.Path;

import java.nio.file.Paths;

import java.nio.file.attribute.FileAttribute;

import java.nio.file.attribute.PosixFilePermission;

import java.nio.file.attribute.PosixFilePermissions; 

 在以前的操作中,主要通过File构造一个文件,然后将File作为入参,获取输入流等操作。Api的操作不是很流畅。在新的文件IO中,用Path取代了File,用Files作为一个操作类,并且封装了很多非常实用的Api,看完下面的示例,就会有一个新的理解。



package filespaths;
import org.junit.Test;
import java.io.*;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermission;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;
/**
* @Author kingboy
* @Date 2017/4/13 11:05
* @Description Path is used to Path Sample
* @email kingboyworld@163.com
*/
public class PathTest {
 private static String separator = File.separator;
 /**
  * 构建Path
  */
 @Test
 public void constructon(){
   //1.Paths
   Path path = Paths.get("/Users/kingboy/Desktop/");
   Path path1 = Paths.get(URI.create("/Users/kingboy/Desktop/"));
   //2.FileSystems
   Path path2 = FileSystems.getDefault().getPath("/Users/kingboy/Desktop/");
   //3.File
   Path path3 = new File("/Users/kingboy/Desktop/").toPath();
 }
 /**
  * 创建一个空文件/文件夹
  * @throws IOException
  */
 @Test
 public void create() throws IOException {
   //文件夹
   Path path = Paths.get("/Users/kingboy/Desktop/hello");
   if(!Files.exists(path)){
     Files.createDirectory(path);
     //创建多个目录
     //Files.createDirectories(path);
   }
   //文件
   Path path1 = Paths.get("/Users/kingboy/Desktop/helloFile");
   if(Files.exists(path1)){
     Files.createFile(path1);
   }
 }
 /**
  * 文件属性
  */
 @Test
 public void getFileProperties() throws IOException {
   Path path = Paths.get("/Users/kingboy/Desktop/text.txt");
   System.out.println(Files.getLastModifiedTime(path));//最后修改时间
   System.out.println(Files.getOwner(path));//拥有者
   System.out.println(Files.getPosixFilePermissions(path));//权限
   System.out.println(Files.size(path));//文件大小
 }
 /**
  * 读取一个文本文件
  */
 @Test
 public void readText() throws IOException {
   Path path = Paths.get("/Users/kingboy/Desktop/text.txt");
   //通过bufferedReader读取
   BufferedReader bufferedReader = Files.newBufferedReader(path, StandardCharsets.UTF_8);//文件编码
   StringBuilder sb = new StringBuilder();
   String tempString = null;
   while ((tempString = bufferedReader.readLine())!=null){
     sb = sb.append(tempString);
   }
   System.out.println(sb);
   //通过Files方法readAllLines
   List<String> strings = Files.readAllLines(path);
   strings.forEach(s -> System.out.print(s));
   //输出结果
   //adsfasdfasdfadsfasdfgsdfsdffsdfsdf
   //adsfasdfasdfadsfasdfgsdfsdffsdfsdf
 }
 /**
  * 拿到文件输入流
  * @throws IOException
  */
 @Test
 public void getInputStream() throws IOException {
   Path path = Paths.get("/Users/kingboy/Desktop/text.txt");
   InputStream inputStream = Files.newInputStream(path);
 }
 /**
  * 文件写操作
  */
 @Test
 public void writeFile() throws IOException {
   Path path = Paths.get("/Users/kingboy/Desktop/writeFile");
   BufferedWriter bufferedWriter = Files.newBufferedWriter(path);
   String str = "write file test";
   bufferedWriter.write(str);
   bufferedWriter.flush();
   bufferedWriter.close();
 }
 /**
  * 遍历一个文件夹
  */
 @Test
 public void traverseDirectory() throws IOException {
   Path path = Paths.get("/Users/kingboy/Desktop/");
   Stream<Path> list = Files.list(path);
   list.forEach(p -> {
     System.out.println(p.getFileName());
   });
 }
 /**
  * 遍历文件树
  */
 @Test
 public void traverseTree() throws IOException {
   Path path = Paths.get("/Users/kingboy/Desktop/");
   Stream<Path> walk = Files.walk(path);
   walk.forEach(path1 -> {
//      System.out.println(path1.getRoot());//根目录
     System.out.println(path1.getFileName());//文件名
//      System.out.println(path1.getParent());//上级目录
//      System.out.println(path1.getFileSystem());//文件系统
   });
   //还有种方式Files.walkFileTree()
 }
 /**
  * 文件复制
  */
 @Test
 public void copyFile() throws IOException {
   Path path = Paths.get("/Users/kingboy/Desktop/text.txt");
   Path path2 = Paths.get("/Users/kingboy/Desktop/hello.txt");
   Files.copy(path,path2);
 }
 /**
  * 读取权限见上面示例,设置权限
  */
 @Test
 public void writePermission() throws IOException {
   Path path = Paths.get("/Users/kingboy/Desktop/text.txt");
   Set<PosixFilePermission> permissionSet = new HashSet<>();
   permissionSet.add(PosixFilePermission.GROUP_WRITE);
   permissionSet.add(PosixFilePermission.OWNER_EXECUTE);
   Files.setPosixFilePermissions(path,permissionSet);
 }
 //还有很多其他操作Api,自己查看方法名,很容易就能分辨出功能。
}

希望本篇文章对需要的朋友有帮助

标签:java,Path,Paths,Files
0
投稿

猜你喜欢

  • Android之软键盘自动弹出和关闭【代码分享】

    2021-06-30 16:26:08
  • 详解Java的文件与目录管理以及输入输出相关操作

    2022-05-03 15:07:22
  • Spring实现默认标签解析流程

    2021-07-29 10:07:55
  • java返回集合为null还是空集合及空集合的三种写法小结

    2021-08-18 05:37:48
  • java基础-数组扩容详解

    2022-05-24 00:34:58
  • idea如何配置javafxsdk详细教程

    2023-11-24 22:04:16
  • Java之BigDecimal的坑及解决

    2022-05-17 01:09:01
  • 深入理解Kotlin的泛型系统

    2023-09-09 00:47:30
  • C# 打开蓝牙设置界面的两种方法

    2021-12-22 04:51:43
  • 深入浅析Java中普通代码块、构造代码块与静态代码块

    2023-04-14 15:16:35
  • SpringBoot项目Jar包如何瘦身部署的实现

    2021-09-21 05:37:51
  • Java 字符串转float运算 float转字符串的方法

    2022-04-09 10:09:06
  • SQL语句删除和添加外键、主键的方法

    2023-04-16 22:18:35
  • java使用正则表达校验手机号码示例(手机号码正则)

    2022-04-07 20:37:04
  • datatables 带查询条件java服务端分页处理实例

    2023-12-24 08:48:16
  • Android RecyclerView添加搜索过滤器的示例代码

    2022-03-08 21:44:49
  • 使用IDEA搭建SSM框架的详细教程(spring + springMVC +MyBatis)

    2023-04-24 07:35:45
  • Android CheckBox中设置padding无效解决办法

    2022-09-07 01:35:48
  • Java实现特定范围的完数输出算法示例

    2023-11-29 00:43:45
  • Android Studio一直处于Building的两种解决方法

    2022-06-13 23:05:22
  • asp之家 软件编程 m.aspxhome.com