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);
}
}
}