Java IO——Files類和Paths
Java的JDK7發生了很大的變化,專門引入了很多類:
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;
......等等,來取代原來的基於java.io.File的檔案IO操作方式.
public class PathsDemo {
public static void main(String[] args) {
// 1)首先是final類Paths的兩個static方法,如何從一個路徑字串來構造Path物件:
Path p1=Paths.get("D:/","a");
Path p2=Paths.get("D://a//b");
URI uri=URI.create("file:///D://a//c");
Path p3=Paths.get(uri);
//2)FileSystems構造
Path p4=FileSystems.getDefault().getPath("D://a//aa.log");
//3)File和Path之間的轉換,File和URI之間的轉換:
File file=new File("D://my.txt");
Path p5=file.toPath();
URI u=file.toURI();
System.out.println(p5);
System.out.println(u);
//4)建立檔案
Path p6=Paths.get("D://a//a.txt");
try {
if(!Files.exists(p6)) {
Files.createFile(p6);
System.out.println("檔案建立成功!");
}else {
System.out.println("檔案已存在!");
}
}catch(Exception e) {
e.getStackTrace();
}
//5)檔案寫操作
BufferedWriter bw;
try {
bw = Files.newBufferedWriter(Paths.get("D:\\a\\a.txt"), StandardCharsets.UTF_8);
bw.write("Are you ok?");
bw.write("I'm fine!");
bw.flush();
bw.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//6)Files.newBufferedReader讀取檔案
try {
BufferedReader reader=Files.newBufferedReader(Paths.get("D:\\a\\a.txt"),StandardCharsets.UTF_8);
String str=null;
while((str=reader.readLine())!=null) {
System.out.println(str);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 7)遍歷一個資料夾:
Path dir=Paths.get("D://a");
try(DirectoryStream<Path> stream=Files.newDirectoryStream(dir)){
for(Path s:stream) {
System.out.println(s.getFileName());
}
}catch(Exception e) {
}
//7.1)遍歷單個目錄
try(Stream<Path> stream=Files.list(Paths.get("D:/"))){
Iterator<Path> it=stream.iterator();
while(it.hasNext()) {
Path p=it.next();
System.out.println(p.getFileName());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 8)遍歷整個檔案目錄
Path allDir=Paths.get("C:\\Users\\admin\\eclipse-workspace\\taotao1211");
List<Path> result=new LinkedList<Path>();
try {
Files.walkFileTree(allDir, new FindJavaVisitor(result));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("reslut.size()="+result.size());
}
private static class FindJavaVisitor extends SimpleFileVisitor<Path>{
private List<Path> result;
public FindJavaVisitor(List<Path> result) {
this.result =result;
}
public FileVisitResult visitFile(Path file,BasicFileAttributes attr) {
if(file.toString().endsWith(".java")) {
result.add(file.getFileName());
}
return FileVisitResult.CONTINUE;
}
}
}
9)將目錄下面所有符合條件的圖片刪除掉:filePath.matches(".*_[1|2]{1}\\.(?i)(jpg|jpeg|gif|bmp|png)")
public class PathsDemo02 {
public static void main(String[] args) {
// TODO Auto-generated method stub
URI uri=URI.create("D://a");
Path allDir=Paths.get(uri);
List<Path> result=new LinkedList<Path>();
try {
Files.walkFileTree(allDir, new FindJavaVisitor(result));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("result.size()"+result.size());
}
private static class FindJavaVisitor extends SimpleFileVisitor<Path>{
private List<Path> result;
public FindJavaVisitor(List<Path> result) {
this.result=result;
}
public FileVisitResult visitFile(Path file,BasicFileAttributes attrs) {
String filePath=file.toFile().getAbsolutePath();
if(filePath.matches(".*_[1|2]{1}\\.(?i)(jpg|jpeg|gif|bmp|png)")) {
try {
Files.deleteIfExists(file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
result.add(file.getFileName());
}
return null;
}
}
}
}
轉載自:https://blog.csdn.net/u010889616/article/details/52694061