博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
关于对文件的操作
阅读量:5085 次
发布时间:2019-06-13

本文共 6920 字,大约阅读时间需要 23 分钟。

(1)遍历指定文件夹,输出带有.txt和.java的文件

package Demo1;import java.io.IOException;import java.nio.file.FileSystem;import java.nio.file.FileSystems;import java.nio.file.FileVisitResult;import java.nio.file.Files;import java.nio.file.LinkOption;import java.nio.file.Path;import java.nio.file.PathMatcher;import java.nio.file.Paths;import java.nio.file.SimpleFileVisitor;import java.nio.file.attribute.BasicFileAttributes;import java.util.ArrayList;public class FileFinder extends SimpleFileVisitor
{ @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Path name=file.getFileName(); System.out.println("Examining "+name); if(matcher.matches(name)){ foundPaths.add(file); } return FileVisitResult.CONTINUE; } private PathMatcher matcher; public ArrayList
foundPaths=new ArrayList<>(); public FileFinder(String pattern){ matcher=FileSystems.getDefault().getPathMatcher("glob:"+pattern); } public static void main(String[] args) { Path fileDir=Paths.get("E:\\Eclipse IDE for java developers"); FileFinder finder1=new FileFinder("*.java"); FileFinder finder2=new FileFinder("*.txt"); try { Files.walkFileTree(fileDir, finder1); Files.walkFileTree(fileDir, finder2); ArrayList
foundFiles=finder1.foundPaths; ArrayList
foundFiles1=finder2.foundPaths; if(foundFiles.size()>0){ for (Path path : foundFiles) { System.out.println(path.toRealPath(LinkOption.NOFOLLOW_LINKS)); } } else { System.out.println("No files were found!"); } if(foundFiles1.size()>0){ for (Path path : foundFiles1) { System.out.println(path.toRealPath(LinkOption.NOFOLLOW_LINKS)); } } else { System.out.println("No files were found!"); } } catch (IOException e) { e.printStackTrace(); } }}

 

输出结果:

 

 (2)输出大小为1M的文件

import java.io.IOException;import java.io.RandomAccessFile;import java.nio.file.FileSystems;import java.nio.file.FileVisitOption;import java.nio.file.FileVisitResult;import java.nio.file.FileVisitor;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.PathMatcher;import java.nio.file.Paths;import java.nio.file.attribute.BasicFileAttributes;import java.util.EnumSet;public class Search implements FileVisitor { private final PathMatcher matcher; private final long accepted_size; public Search(String glob,long accepted_size) {      matcher= FileSystems.getDefault().getPathMatcher("glob:" +glob);      this.accepted_size=accepted_size;     }   void search(Path file) throws IOException {    long size = (Long) Files.getAttribute(file, "basic:size");    if(size ==accepted_size) {     System.out.println(file);    }   }   @Override   public FileVisitResult postVisitDirectory(Object dir, IOException exc)throws IOException {    return FileVisitResult.CONTINUE;   }   @Override   public FileVisitResult preVisitDirectory(Object dir, BasicFileAttributes attrs)throws IOException {    return FileVisitResult.CONTINUE;   }   @Override   public FileVisitResult visitFile(Object file, BasicFileAttributes attrs)throws IOException {  search((Path) file);     return  FileVisitResult.CONTINUE;  }   @Override   public FileVisitResult visitFileFailed(Object file, IOException exc)throws IOException {  return FileVisitResult.CONTINUE;   }   public static void main(String[] args) throws IOException{    String glob= "*.jpg";    long size = 1048576;//1M=1024k=1048576字节    RandomAccessFile f = new RandomAccessFile("E:\\f1.txt", "rw");    f.setLength(1024 * 1024);  //设置其大小为1M。    Path fileTree = Paths.get("E:\\f1");    Search walk=new Search(glob, size);    EnumSet opts=EnumSet.of(FileVisitOption.FOLLOW_LINKS);    System.out.println("E盘f1文件中中大小等于1M的文件有");    Files.walkFileTree(fileTree, opts, Integer.MAX_VALUE, walk);   }}

结果:

 

 

 由于没有恰好1M的文件,所以我用了代码:

RandomAccessFile f = new RandomAccessFile("E:\\f1.txt", "rw");    f.setLength(1024 * 1024);  //设置其大小为1M。

将此文件设为恰好1M。

(3)找出包容指定字符串的TXT文件

  

import java.nio.file.FileVisitResult;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.PathMatcher;import java.nio.file.Paths;import java.nio.file.SimpleFileVisitor;import java.nio.file.attribute.BasicFileAttributes;public class filesearch {     public static void main(String args[]) throws IOException {            String glob = "glob:**/*.txt";            String path = "E:\\f1";            match(glob, path);        }        public static void match(String glob, String location) throws IOException {            final PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher( glob);            Files.walkFileTree(Paths.get(location), new SimpleFileVisitor
() { @Override public FileVisitResult visitFile(Path path,BasicFileAttributes attrs) throws IOException { if (pathMatcher.matches(path)) { BufferedReader reader =Files.newBufferedReader(path);//读取文件内的内容 String line=null; while((line = reader.readLine()) !=null) { if(line=="ABC")//若读取的内容等于“ABC"则输出文件名 { System.out.println(path); break; } else { System.out.println("没有对应文件"); } } } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { return FileVisitResult.CONTINUE; } }); }}

结果:

(5)计算文件总容量

package Demo1;import java.io.File;import java.util.ArrayList;public class Size {    static long size = 0;    private static ArrayList
filelist = new ArrayList
(); public static void main(String[] args) { Size s = new Size(); String filePath = "E:\\f1"; s.getFiles(filePath); } void getFiles(String filePath) { File root = new File(filePath); File[] files = root.listFiles(); for (File file : files) { if (file.isDirectory()) { getFiles(file.getAbsolutePath()); filelist.add(file.getAbsolutePath()); } else { size += file.getAbsolutePath().length(); } } System.out.println("总容量是" + size); }}

结果:

 

转载于:https://www.cnblogs.com/YXSZ/p/9977451.html

你可能感兴趣的文章
C#中async/await中的异常处理
查看>>
新一代的IT实验室长啥样?
查看>>
SQL Server 2005存储过程示例
查看>>
mouseup,mousedown,mousemove,弹出框拖动效果,javascript
查看>>
python:函数和循环判断
查看>>
js 类对象
查看>>
函数可变参传值(python)
查看>>
单双击响应事件处理区分
查看>>
nio通道
查看>>
ORA-12154: TNS: 无法解析指定的连接标识符
查看>>
Java IO模型
查看>>
【2018.11.23】2018WCTest(7)
查看>>
Tomcat中catalina.bat详解
查看>>
Python的hasattr() getattr() setattr() 函数使用方法详解
查看>>
Java注解简单学习
查看>>
ZooKeeper系列3:ZooKeeper命令、命令行工具及简单操作
查看>>
VMware exsi 虚拟化嵌套
查看>>
java.lang.NoClassDefFoundError: javax/servlet/jsp/jstl/core/Config
查看>>
div模态层示例
查看>>
转:ASP.NET发布WebService操作流程
查看>>