07【Path、Files类的使用】

本文详细介绍了Java NIO中的Path和Files类,包括Path的创建、获取、比较、拼接和转换方法,以及Files类提供的文件操作、读写、流转等功能。通过示例代码展示了如何使用这些方法进行文件系统操作,帮助理解Java NIO在文件处理上的优势。
摘要由CSDN通过智能技术生成

07【Path、Files类的使用】

7.1 Path

7.1.1 Path简介

Path是一个接口,它用来表示文件系统的路径,可以指向文件或文件夹。也有相对路径和绝对路径之分。Path是在Java 7中新添加进来的。Path接口在java.nio.file包下,所以全称是java.nio.file.Path;Path对象中存在很多与路径相关的功能方法,如获取根路径、获取父路径、获取文件名、拼接路径、返回绝对路径等操作;

在很多方面,java.nio.file.Path接口和java.io.File有相似性,但也有一些细微的差别,Path用起来比File类要方便的多。在很多情况下,可以用Path来代替File类,另外一个Path对象也可以直接转换File对象,一个File对象也可以直接转换为Path对象。

7.1.2 Path相关方法

  • java.nio.file.Paths:
    • static Path get(String first,String... more):通过连接给定的字符串创建一个Path对象
1)Path路径相关方法
  • Path toAbsolutePath() :返回表示此路径的绝对路径的 Path对象。
  • Path toRealPath(LinkOption... options) :返回现有文件的真实路径。
  • boolean isAbsolute() :告诉这条路是否是绝对的。
  • Path normalize():返回一个路径,该路径是冗余名称元素的消除。

示例代码:

package com.dfbz.path;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author lscl
 * @version 1.0
 * @intro:
 */
public class Demo01_Path路径相关方法 {

    public static void main(String[] args) throws IOException {
        Path path = Paths.get("./001.txt");

        // .\001.txt
        System.out.println(path);

        // E:\BaiduNetDiskWorkspace\workspace\IO\NIO\.\001.txt
        System.out.println(path.toAbsolutePath());      // 绝对路径包含相对路径中的那个"./"

        // E:\BaiduNetDiskWorkspace\workspace\IO\NIO\001.txt
        System.out.println(path.toRealPath());          // 真实路径不包含相对路径的那个"./"

        // E:\BaiduNetDiskWorkspace\workspace\IO\NIO\001.txt
        System.out.println(path.toAbsolutePath().normalize());      // 路径优化可以把"./"去掉
    }
}
2)Path获取相关方法
  • Path getName(int index) :返回此路径的名称元素作为 Path对象(文件所在盘符不算元素)。
  • int getNameCount() :返回路径中的名称元素的数量(文件所在盘符不算元素)。
  • Path getFileName():将此路径表示的文件或目录的名称返回为Path对象。
  • Path getParent():返回父路径,如果此路径没有父返回null,如:相对路径
  • Path getRoot():返回此路径的根(盘符)作为Path对象,如果此路径没有根返回null,如:相对路径
  • Path subpath(int beginIndex, int endIndex):截取该路径的beginIndex(含)索引到endIndex(不含)索引的元素
  • Iterator<Path> iterator():返回此路径的名称元素的迭代器。 另外Path继承了Iterator接口,任意的Path对象都可以使用foreach迭代;

示例代码:

package com.dfbz.path;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author lscl
 * @version 1.0
 * @intro:
 */
public class Demo02_Path获取相关方法 {
    public static void main(String[] args) throws IOException {
        Path path = Paths.get("./001.txt");

        Path absPath = path.toAbsolutePath();

        // E:\BaiduNetDiskWorkspace\workspace\IO\NIO\.\001.txt
        System.out.println(absPath);

        // BaiduNetDiskWorkspace\workspace
        System.out.println(absPath.subpath(0,2));

        // workspace\IO
        System.out.println(absPath.subpath(1,3));

        // workspace\IO\NIO\.
        System.out.println(absPath.subpath(1,5));

        // workspace\IO\NIO\.\001.txt
        System.out.println(absPath.subpath(1,6));
    }


    public static void test2(String[] args) throws IOException {
        Path path = Paths.get("./001.txt");

        // E:\BaiduNetDiskWorkspace\workspace\IO\NIO\.\001.txt
        Path absPath = path.toAbsolutePath();

        // E:\BaiduNetDiskWorkspace\workspace\IO\NIO\001.txt
        Path realPath = path.toRealPath();

        /*
         6("./"也算一个元素,注意该方法并没有纳入盘符元素)
         ["BaiduNetDiskWorkspace","workspace","IO","NIO",".","001.txt"]
         */
        System.out.println(absPath.getNameCount());

         /*
         5(注意该方法并没有纳入盘符元素)
         ["BaiduNetDiskWorkspace","workspace","IO","NIO","001.txt"]
         */
        System.out.println(realPath.getNameCount());

        System.out.println("-----------------------");
        for (Path temp : absPath) {
            System.out.println(temp);
        }
        System.out.println("-----------------------");
        for (Path temp : realPath) {
            System.out.println(temp);
        }
        System.out.println("------------------------");

        // E:\BaiduNetDiskWorkspace\workspace\IO\NIO\.
        System.out.println(absPath.getParent());

        // E:\BaiduNetDiskWorkspace\workspace\IO\NIO
        System.out.println(realPath.getParent());

        // E:\
        System.out.println(absPath.getRoot());

        // E:\
        System.out.println(realPath.getRoot());

    }


    public static void test() throws IOException {
        Path path = Paths.get("./001.txt");

        // .\001.txt
        System.out.println(path);

        // 001.txt
        System.out.println(path.getFileName());

        // .
        System.out.println(path.getParent());

        // null
        System.out.println(path.getRoot());     // 获取的是文件的盘符,相对路径中没有盘符,所以返回null

        // 2
        System.out.println(path.getNameCount());

        // .
        System.out.println(path.getName(0));

        // 001.txt
        System.out.println(path.getName(1));
    }
}
3)Path比较相关方法
  • boolean endsWith(Path other):测试此路径是否以给定的路径结束。
  • boolean endsWith(String other):测试此路径是否以给定的路径结束。
  • boolean startsWith(Path other) :测试此路径是否以给定的路径开始。
  • boolean startsWith(String other) :测试此路径是否以给定的路径开始。

XxxWith方法比较的是是否以指定"元素"开始或者结束,而不是比较是否以指定字符串开始或结束;首先这个字符串得是一个元素!

示例代码:

package com.dfbz.path;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author lscl
 * @version 1.0
 * @intro:
 */
public class Demo03_Path比较相关方法 {

    public static void main(String[] args) throws IOException {
        Path path = Paths.get("E:\\BaiduNetDiskWorkspace\\workspace\\IO\\NIO\\001.txt");

        System.out.println(path.startsWith("E"));       // false,E并不是一个元素
        System.out.println(path.startsWith("E:"));       // false,E并不是一个元素
        System.out.println(path.endsWith("txt"));       // false,txt并不是一个元素

        System.out.println("---------------");

        System.out.println(path.startsWith("E:\\"));                // true
        System.out.println(path.startsWith("E:\\BaiduNet"));        // false
        System.out.println(path.startsWith("E:\\BaiduNetDiskWorkspace"));        // true
        System.out.println(path.startsWith("E:\\BaiduNetDiskWorkspace\\"));        // true

        System.out.println("-----------------------");
        System.out.println(path.endsWith("001.txt"));                   // true
        System.out.println(path.endsWith("O\\001.txt"));                // false
        System.out.println(path.endsWith("NIO\\001.txt"));              // true
        System.out.println(path.endsWith("\\NIO\\001.txt"));          // false
    }
}
4)Path拼接相关方法
  • Path resolve(Path other):返回连接this和other获取的路径
  • Path resolve(String other):返回连接this和other获取的路径
  • Path resolveSibling(String other):返回连接this的父路径和other获取的路径,如果是想对路径则直接将this替换为other
  • Path resolveSibling(String other):返回连接this的父路径和other获取的路径,如果是想对路径则直接将this替换为other

示例代码:

package com.dfbz.path;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author lscl
 * @version 1.0
 * @intro:
 */
public class Demo04_Path拼接相关方法 {

    public static void main(String[] args) throws IOException {
        Path path1 = Paths.get("E:\\BaiduNetDiskWorkspace\\workspace\\IO\\NIO\\001.txt");
        Path path2 = Paths.get("001.txt");

        // E:\BaiduNetDiskWorkspace\workspace\IO\NIO\001.txt\002.txt
        System.out.println(path1.resolve("002.txt"));

        // 001.txt\002.txt
        System.out.println(path2.resolve("002.txt"));

        System.out.println("---------------------------------");

        // E:\BaiduNetDiskWorkspace\workspace\IO\NIO\002.txt
        System.out.println(path1.resolveSibling("002.txt"));

        // 002.txt
        System.out.println(path2.resolveSibling("002.txt"));
    }
}
5)File与Path的转换
  • java.nio.file.Path:
    • File toFile() :返回表示此路径的File对象。
    • String toString() :返回此路径的字符串表示形式。
    • URI toUri() :返回一个URI来表示此路径。
    • static Path of(String first, String... more):构建一个Path对象;
  • java.io.File:
    • Path toPath():将该File转换为Path对象

示例代码:

package com.dfbz.path;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author lscl
 * @version 1.0
 * @intro:
 */
public class Demo05_FilePath的转换 {

    public static void main(String[] args) {

        // 构建一个新的Path
        Path path = Path.of("001.txt");
        System.out.println(path);                                                   // 001.txt

        // 通过多级目录来构建Path
        System.out.println(Path.of("aaa", "bbb", "000.txt"));     // aaa\bbb\000.txt
    }

    public static void test3(String[] args) throws URISyntaxException {
        URI uri = new URI("001.txt");

        // 通过URI来构建File
        File file = new File(uri);
        System.out.println(file);

        // 通过uri来构建Path
        Path path = Paths.get(uri);
        System.out.println(path);
    }

    public static void test2(String[] args) {
        File file = new File("001.txt");

        // File转Path
        Path path = file.toPath();
        System.out.println(path);

        // File转RRI
        URI uri = file.toURI();
        System.out.println(uri);
    }

    public static void test(String[] args) throws IOException {
        Path path = Paths.get("001.txt");

        // Path转换为File
        File file = path.toFile();
        System.out.println(file);

        // Path转换为URI
        URI uri = path.toUri();
        System.out.println(uri);
    }
}

7.2 Files类

7.2.1 Files类简介

Files类是一个强大的文件处理类,它可以帮助我们类似与一个文件操作的工具类,可以使得普通文件操作变得快捷;

7.2.2 Files类相关方法

1)文件的操作
  • 文件/文件夹的判断方法:
返回值方法名说明
long size(Path path) 返回文件大小
booleanisDirectory(Path path) 是否是文件夹
booleanisExecutable(Path path)是否是可执行文件
booleanisHidden(Path path) 是否是隐藏的
booleanexists(Path path) 该文件/文件夹是否存在
booleannotExists(Path path) 是否不存在
booleanisReadable(Path path) 是否可读
booleanisWritable(Path path) 是否可写
  • 移动文件/文件夹:
返回值方法名说明
PathFiles.move(Path src, Path target)剪切,如果目标已存在,会报错
Pathpublic static Path move(Path source, Path target, CopyOption... options)如果目标已存在,会替换
  • 复制文件/文件夹:
返回值方法名说明
PathFiles.copy(Path src, Path target)复制文件,如果存在同名的目标文件,会报错。
Pathpublic static Path copy(Path source, Path target, CopyOption... options)如果存在同名的目标文件,会替换只能是文件,不能是文件夹(只能复制空的文件夹)
  • 删除文件/目录:
返回值方法名说明
PathFiles.delete(Path path)删除文件、空目录。如果不存在,会报错
PathFiles.deleteIfExists(Path path)存在才删除,不存在时不会报错。
  • 创建文件/目录:
返回值方法名说明
PathcreateFile(Path filePath)创建文件,只能是文件,不能是文件夹。如果已存在同名文件,会报错。
PathcreateDirectory(Path dirPath)创建文件夹。如果已存在同名文件夹,会报错
  • 示例代码:
package com.dfbz.files;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

/**
 * @author lscl
 * @version 1.0
 * @intro:
 */
public class Demo01_文件的操作 {

    /**
     * 文件/文件夹的判断
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {

        // 是否是文件夹
        System.out.println(Files.isDirectory(Path.of("001")));

        // 文件或文件夹是否存在
        System.out.println(Files.exists(Path.of("001")));

        // 文件或文件夹是否是隐藏
        System.out.println(Files.isHidden(Path.of("001")));

        // 文件或文件夹是否是可读
        System.out.println(Files.isReadable(Path.of("001")));

        // 文件或文件夹是否是可写
        System.out.println(Files.isWritable(Path.of("001")));

        // 文件或文件夹是否是可执行
        System.out.println(Files.isExecutable(Path.of("001")));

        // 返回文件的大小(文件夹将会直接返回0)
        long size = Files.size(Path.of("001.txt"));
        System.out.println(size);
    }

    /**
     * 移动文件/文件夹
     *
     * @param args
     * @throws Exception
     */
    public static void test4(String[] args) throws Exception {
        // 将001.txt移动到000目录下,并命名为aaa.txt
//        Files.move(Path.of("000.txt"),Path.of("./000/aaa.txt"));

        // 相当于剪切操作
        Files.move(Path.of("000"), Path.of("001"));
    }

    /**
     * 复制文件/文件夹
     *
     * @param args
     * @throws Exception
     */
    public static void test3(String[] args) throws Exception {

        // 只能复制空的文件夹,即使文件中存在很多文件(相当于拷贝文件夹)
//        Files.copy(Path.of("000"),Path.of("001"));

        // 将001.txt复制到000目录下,并命名为bbb.txt
//        Files.copy(Path.of("001.txt"),Path.of("./000/bbb.txt"));

        FileOutputStream fos = new FileOutputStream("003.txt");
        // 将001.txt中的字节复制到指定的输出流中
        Files.copy(Path.of("001.txt"), fos);
        fos.close();
    }

    /**
     * 删除文件/目录
     *
     * @param args
     * @throws IOException
     */
    public static void test2(String[] args) throws IOException {

        // 删除文件或文件夹,该文件或文件夹必须存在(删除文件夹时,文件夹必须是空的,不能包含其他文件或文件夹)
//        Files.delete(Path.of("000"));

        // 如果该文件或文件夹存在就删除
        Files.deleteIfExists(Path.of("000"));
    }

    /**
     * 创建文件/目录
     *
     * @param args
     * @throws Exception
     */
    public static void test1(String[] args) throws Exception {

        // 创建目录(该方法不能创建多级目录)
        Files.createDirectory(Path.of("000"));

        // 创建多级目录
        Files.createDirectories(Path.of("111\\222\\333"));

        // 创建文件(该文件不能存在)
        Files.createFile(Path.of("002.txt"));
    }
}
2)读取和写入
  • 读取相关方法:
返回值方法名说明
String String Files.readString(Path path) 读取所有文本,以String形式返回。会读取换行符。只能是文本文件
String Files.readString(Path path, Charset charset) 可指定解码字符集
List<String> Files.readAllLines(Path path) 读取所有的行,以LIst形式返回,一行就是一个String类型的元素。只能是文本文件
List<String> Files.readAllLines(Path path, Charset charset)可指定解码字符集
byte[] Files.readAllBytes(Path path) 读取文件所有数据,以字节数组形式返回。文件可以是任意类型。
  • 写入相关方法:
返回值方法名说明
Path Files.write(Path path, byte[] bytes) 写入一个byte[]
PathFiles.writeString(Path path, CharSequence cs) 写入一个字符序列,可以是String、StringBuffer、StringBuilder、Char[]
PathFiles.writeString(Path path, CharSequence cs, Charset charset)指定编码字符集
  • 示例代码:
package com.dfbz.files;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;
import java.util.List;

/**
 * @author lscl
 * @version 1.0
 * @intro:
 */
public class Demo01 {

    public static void main(String[] args) throws Exception {
        // 写出字符串
        Files.writeString(Path.of("001.txt"), "你好");

        // 按照指定的编码表写出字符串
        Files.writeString(Path.of("001.txt"), "UTF-8");

        // 追加内容
        Files.writeString(Path.of("001.txt"), "UTF-8", StandardOpenOption.APPEND);
    }

    /**
     * 写字节
     *
     * @param args
     * @throws Exception
     */
    public static void test2(String[] args) throws Exception {
        // 往文件中写入字节
        byte[] data = {97, 98, 99};
        Files.write(Path.of("001.txt"), data);

        // 往文件中写内容
        List<String> lines = Arrays.asList("你好", "我好", "大家好");
        Files.write(Path.of("001.txt"), lines);

        // 追加内容
        Files.write(Path.of("001.txt"), "我是追加的内容".getBytes(), StandardOpenOption.APPEND);
    }

    /**
     * 读取数据
     *
     * @param args
     * @throws IOException
     */
    public static void test(String[] args) throws IOException {

        // 读取数据
        byte[] data = Files.readAllBytes(Paths.get("001.txt"));
        System.out.println(new String(data));

        System.out.println("------------------");

        // 使用默认的编码表读取字符串
        String str = Files.readString(Paths.get("001.txt"));
        System.out.println(str);

        System.out.println("------------------");

        // 指定编码表读取字符串
        String str2 = Files.readString(Paths.get("001.txt"), Charset.forName("UTF-8"));
        System.out.println(str2);
        System.out.println("-----------------------");

        // 按行读取数据,每一行数据都是一个字符串
        List<String> lines = Files.readAllLines(Path.of("001.txt"));
        for (String line : lines) {
            System.out.println(line);
        }
    }
}
3)文件与流
返回值方法名说明
BufferedReader Files.newBufferedReader(Path path)可指定解码字符集
BufferedReader Files.newBufferedReader(Path path,Charset charset)
BufferedWriter Files.newBufferedWriter(Path path)
BufferedWriter Files.newBufferedWriter(Path path, Charset charset)可指定编码字符集
InputStream Files.newInputStream(Path path)
OutputStream Files.newOutputStream(Path path)
SeekableByteChannelnewByteChannel(Path path, OpenOption... options) 获取Channel
  • 示例代码:
package com.dfbz.files;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

/**
 * @author lscl
 * @version 1.0
 * @intro:
 */
public class Demo03_文件与流 {

    /**
     * 通过Path获取Channel
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        // 通过Path构建Channel
        SeekableByteChannel channel = Files.newByteChannel(Path.of("001.txt"),
                // 设置可读
                StandardOpenOption.READ,

                // 设置可写
                StandardOpenOption.WRITE,

                // 设置追加
                StandardOpenOption.APPEND
        );
        channel.write(ByteBuffer.wrap("hello".getBytes()));
        channel.close();
    }

    /**
     * 通过Path获取流
     *
     * @param args
     * @throws Exception
     */
    public static void test(String[] args) throws Exception {

        InputStream is = Files.newInputStream(Path.of("001.txt"));
        OutputStream os = Files.newOutputStream(Path.of("004.txt"));

        BufferedReader br1 = Files.newBufferedReader(Path.of("005.txt"));
        BufferedReader br2 = Files.newBufferedReader(Path.of("005.txt"), Charset.forName("UTF-8"));

        BufferedWriter bw1 = Files.newBufferedWriter(Path.of("006.txt"));
        BufferedWriter bw2 = Files.newBufferedWriter(Path.of("006.txt"), Charset.forName("GBK"));
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

緑水長流*z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值