1.Path类;java.nio.file.Path,用于来表示文件路径和文件。
public static Path get(String first, String... more) ;
Path path1 = Paths.get("C:", "aaa/bbb/ccc");
Path path2 = Paths.get("C:/aaa/bbb/ccc");
Path path3 = Paths.get("C:","aaa","bbb","ccc");
2.Files类;java.nio.file.Files,包含一组对文件、目录进行操作的静态方法。
Files.exists(path1);
Files.notExists(path1);
Files.createFiles(path1);
Files.createDirectories(path1);
BufferedReader reader = Files.newBufferedReader(path1,Charset.forName("gbk"));
BufferedWrite write = Files.newBufferedWrite(path1);
List<String> lines = Files.readAllines(path1);
List<String> lines = Files.readAllined(Path1,Charset.forName("gbk"));
DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get("C:"));
DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get("C:"),"*.{jpg,png,txt}");
Files.copy(path1, System.out);
Files.copy(System.in, path1 ,StandardCopyOption.REPLACE_EXISTING);
Files.copy(path1, Paths.get("C:/datax.txt"),StandardCopyOption.REPLACE_EXISTING);
Files.move(path1, Paths.get("C:/temp.txt"),StandardCopyOption.REPLACE_EXISTING);
Files.delete(Paths.get("C:/temp.txt"))
3.同过Files类遍历一个文件夹中的所有文件。
public class Deam01 {
public static void main(String[] args) {
String str = "C:\\Users\\10417\\Desktop\\文件夹\\猿究院";
File file = new File(str);
getFiles(file);
}
public static void getFiles(File file) {
File[] files = file.listFiles();
for (File f : files) {
if(f.isDirectory()) {
getFiles(f);
}else {
System.out.println(f.getName());
}
}
}
}
- 使用Files类的walkFileTree方法遍历。
public class Deam02 {
public static void main(String[] args) {
String str = "C:\\Users\\10417\\Desktop\\文件夹\\猿究院";
try {
Files.walkFileTree(Paths.get(str), new MyFileVisitor());
} catch (IOException e) {
e.printStackTrace();
}
}
}
class MyFileVisitor extends SimpleFileVisitor<Path>{
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
System.out.println("文件 --> " + file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
System.out.println("目录 --> " + dir);
return FileVisitResult.CONTINUE;
}
}