通过NIO操作文件

1、基本操作

package com.individual.nio;

import com.google.common.collect.Lists;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.util.Date;
import java.util.List;

public class BasicFileOperation {
    public static void main(String[] args) throws IOException {
        copyFileFromInternet();
    }

    // 创建文件夹
    public static void createDirectory() throws IOException {
        Path path = Paths.get("c:/temp");
        Files.createDirectory(path);
    }

    // 创建文件
    public static void createFile() throws IOException {
        Path path = Paths.get("c:/temp/temp.txt");
        Files.createFile(path);
    }

    // 判断文件或文件夹是否存在
    public static void judgmentFileOrDirectoryIsP() throws IOException {
        Path filePath = Paths.get("c:/temp/temp.txt");
        Path directoryPath = Paths.get("c:/temp/test");
        System.out.println(Files.exists(filePath));
        System.out.println(Files.exists(directoryPath));
    }

    // 创建Path对象
    public static void createPathMethod() {
        // 方式1
        Path path = FileSystems.getDefault().getPath("C:/", "temp.txt");
        // 方式2
        File file = new File("c:/temp.txt");
        Path path1 = file.toPath();
        // 方式3
        Path path2 = Paths.get("C:/", "temp.txt");
        // 合并两个Path
        Path path3 = Paths.get("C:/");
        Path path4 = Paths.get("temp.txt");
        Path resolve = path3.resolve(path4);
        // Path和字符串拼接
        Path path5 = Paths.get("D:/");
        Path resolve1 = path5.resolve("temp.txt");
    }

    // 判断是文件还是文件夹
    public static void judgmentFileOrDirectory() {
        Path directoryPath = Paths.get("c:/");
        Path filePath = directoryPath.resolve("temp.txt");
        boolean directory = Files.isDirectory(directoryPath);
        boolean file = Files.isDirectory(filePath);
    }

    // 判断文件或文件夹是否可读
    public static void judgmentFileOrDirectoryIsReadable() {
        Path directoryPath = Paths.get("c:/");
        Path filePath = directoryPath.resolve("temp.txt");
        boolean directoryReadable = Files.isReadable(directoryPath);
        boolean fileReadable = Files.isReadable(filePath);
    }

    // 获取父文件夹Path
    public static void getParentPath() {
        Path path = Paths.get("c:/", "temp.txt");
        Path parent = path.getParent();
    }

    // 获取文件大小
    public static void getFileSize() throws IOException {
        Path path = Paths.get("c:/", "temp/", "temp.txt");
        System.out.println(Files.size(path));
    }

    // 移动文件并重命名
    public static void moveFileAndRename() throws IOException {
        Path from = Paths.get("c:/", "temp/", "temp.txt");
        Path toDirectory = from.getParent().resolve("test/");
        if (Files.notExists(toDirectory)) {
            Files.createDirectory(toDirectory);
        }
        Path to = toDirectory.resolve("def.txt");
        Files.move(from, to, StandardCopyOption.REPLACE_EXISTING);
    }

    // 获取文件属性
    public static void getFileAttributes() throws IOException {
        Path path = Paths.get("c:/temp/test/def.txt");
        BasicFileAttributes basicFileAttributes = Files.readAttributes(path, BasicFileAttributes.class);
        System.out.println(basicFileAttributes.isDirectory());
        FileTime fileTime = basicFileAttributes.lastModifiedTime();
        System.out.println(new Date(fileTime.toMillis()).toLocaleString());
    }

    // 遍历文件夹下所有文件
    public static void traversalFolder() {
        Path path = Paths.get("c:/temp/test/");
        try (DirectoryStream<Path> paths = Files.newDirectoryStream(path)) {
            for (Path path1 : paths) {
                System.out.println(path1.getFileName());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 过滤文件夹下后缀名为c和txt的所有文件
    public static void filterFiles() throws IOException {
        Path path = Paths.get("c:/temp/test/");
        List<Path> list = Lists.newArrayList();
        list.add(path.resolve("A.c"));
        list.add(path.resolve("B.c"));
        list.add(path.resolve("C.d"));
        list.add(path.resolve("D.d"));
        list.add(path.resolve("E.txt"));
        list.add(path.resolve("F.txt"));
        for (Path p : list) {
            if (Files.notExists(p)) {
                Files.createFile(p);
            }
        }
        // 注:这里有个需要注意的点,c和txt之间只能有逗号,不能有空格
        try (DirectoryStream<Path> paths = Files.newDirectoryStream(path, "*.{c,txt}")) {
            for (Path path1 : paths) {
                System.out.println(path1.getFileName());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 从互联网复制文件到指定目录
    public static void copyFileFromInternet() {
        Path to = Paths.get("C:/temp/test/2.jpg");
        URI uri = URI.create("https://s.cn.bing.net/th?id=OHR.MedievalLabro_ZH-CN0015356188_1920x1080.jpg&rf=LaDigue_1920x1080.jpg");
        try (InputStream from = uri.toURL().openStream()) {
            Files.copy(from, to, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2、搜索文件

package com.individual.nio;

import org.springframework.util.ObjectUtils;

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.EnumSet;
import java.util.Set;

public class SearchFile implements FileVisitor<Path> {
    public static void main(String[] args) throws IOException {
        String ext = "*.jpg"; // 查找后缀名是jpg的文件
        String ext2 = "A.c"; // 查找文件名为A.c的文件
        Path path = Paths.get("c:/");
        SearchFile searchFile = new SearchFile(ext2);
        Set<FileVisitOption> options = EnumSet.of(FileVisitOption.FOLLOW_LINKS);
        Files.walkFileTree(path, options, Integer.MAX_VALUE, searchFile);
    }

    private final PathMatcher matcher;

    public SearchFile(String ext) {
        matcher = FileSystems.getDefault().getPathMatcher("glob:" + ext);
    }

    @Override
    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
        Path fileName = file.getFileName();
        if (!ObjectUtils.isEmpty(fileName) && matcher.matches(fileName)) {
            System.out.println("Searched file was found in: " + file.toRealPath());
        }
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
        return FileVisitResult.CONTINUE;
    }
}

3、遍历文件夹下所有文件

import java.nio.file.Files;
import java.util.Optional;

Optional<Path> optional;
try(Stream<Path> walk = Files.walk(newPath)) {
    optional = walk.filter(file -> file.getFileName().toString().matches("abc.+\\.jar")).findAny(); // 查找已abc开头的文件
}
if(optional.isPresent()){
    Path filePath = optional.get();
}

4、读写文件

package com.individual.nio;

import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
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 ReadWriteFile {
    public static void main(String[] args) throws IOException {
        bufferedWriteFile();
    }

    // 简单写文件
    public static void simpleWriteFile() throws IOException {
        Path ball_path = Paths.get("C:/temp/test", "abc.txt");
        String msg = "Hello World!!!你好 世界!!!";
        Files.write(ball_path, msg.getBytes());
    }

    // 写文件
    public static void writeFile() throws IOException {
        Path path = Paths.get("C:/temp/test", "wiki.txt");
        Charset charset = StandardCharsets.UTF_8;
        List<String> lines = Lists.newArrayList();
        lines.add("Chinese New Year is coming and my family is very busy.");
        lines.add("It s because ChineseNew Year is very special and important.");
        lines.add("We must prepare many special things to get ready for this festival.");
        lines.add("First, will make a big New Year meal.");
        lines.add("Second, we will make Good-luck wishes.");
        lines.add("Third, we will set off firecrackers.");
        lines.add("New Year meal is delicious and we think that eating some will bring us good luck.");
        lines.add("A long time ago, Chinese people believed red color could bring our good luck too.");
        lines.add("And we set off fire crackers could frighten ghosts away.");
        lines.add("Chinese New Year is very popular between students.");
        lines.add("Because we can have along happy holiday.");
        Files.write(path, lines, charset, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
    }

    // 简单读文件
    public static void simpleReadFile() throws IOException {
        Path path = Paths.get("C:/temp/test", "abc.txt");
        byte[] bytes = Files.readAllBytes(path);
        String s = new String(bytes);
        System.out.println(s);
    }

    // 读文件
    public static void readFile() throws IOException {
        Path path = Paths.get("C:/temp/test", "wiki.txt");
        Charset charset = StandardCharsets.UTF_8;
        List<String> lines = Files.readAllLines(path, charset);
        for (String line : lines) {
            System.out.println(line);
        }
    }

    // 通过缓存写文件:方式1
    public static void bufferedWrite() {
        Path path = Paths.get("C:/temp/test", "aaa.txt");
        Charset charset = StandardCharsets.UTF_8;
        String text = "Vamps Rafa!";
        try (BufferedWriter writer = Files.newBufferedWriter(path, charset, StandardOpenOption.CREATE, StandardOpenOption.APPEND)) {
            writer.write(text);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 通过缓存写文件:方式2
    public static void bufferedWriteFile() {
        Path path = Paths.get("C:/temp/test", "bbb.txt");
        Charset charset = StandardCharsets.UTF_8;
        String string = "String: Bolat RPM Blast 16";
        try (OutputStream outputStream = Files.newOutputStream(path, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
             BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, charset))) {
            writer.write(string);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 通过缓存读文件:方式1
    public static void bufferedRead() {
        Path path = Paths.get("C:/temp/test", "aaa.txt");
        Charset charset = StandardCharsets.UTF_8;
        try (BufferedReader reader = Files.newBufferedReader(path, charset)) {
            String line;
            while (StringUtils.isNotBlank(line = reader.readLine())) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 通过缓存读文件:方式2
    public static void bufferedReadFile() {
        Path path = Paths.get("C:/temp/test", "aaa.txt");
        Charset charset = StandardCharsets.UTF_8;
        try (InputStream inputStream = Files.newInputStream(path);
             BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, charset))) {
            String line;
            while (StringUtils.isNotBlank(line = reader.readLine())) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

5、获取jar包中文件并复制到指定位置

package com.individual.nio;

import java.io.IOException;
import java.net.URI;
import java.nio.file.*;
import java.util.Collections;

public class ReadJarFileByNIO {
    public static void main(String[] args) throws IOException {
        readJarFile();
    }

    public static void readJarFile() throws IOException {
        Path fromPath = Paths.get("D:/maven/ali-repository/org/apache/commons/commons-lang3/3.11");
        URI uri = URI.create("jar:" + fromPath.resolve("commons-lang3-3.11.jar").toUri());
        Path toPath = Paths.get("D:/");
        try (FileSystem fileSystem = FileSystems.newFileSystem(uri, Collections.emptyMap())) {
            Path path = fileSystem.getPath("org/apache/commons/lang3/arch/Processor.class");
            Files.copy(path, toPath.resolve("Processor.class"), StandardCopyOption.REPLACE_EXISTING);
        }
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 213,711评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,079评论 3 387
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 159,194评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,089评论 1 286
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,197评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,306评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,338评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,119评论 0 269
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,541评论 1 306
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,846评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,014评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,694评论 4 337
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,322评论 3 318
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,026评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,257评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,863评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,895评论 2 351

推荐阅读更多精彩内容