Guava---文件操作Files
文章目录
guava复制文件
java NIO复制文件
移动文件
读取文件内容(一行一行读)
读取文件内容(按条件读取)
计算文件hashcode (可对比两个文件是否一样)
写文件
获取某路径目录
获取某路径目录(自定义过滤)
guava复制文件
private static String from = "D:\\自定义代码\\Guava\\guava\\src\\1.txt"; private static String to = "D:\\自定义代码\\Guava\\guava\\src\\2.txt"; Files.copy(new File(from),new File(to));
java NIO复制文件
java.nio.file.Files.copy(Paths.get(from),
Paths.get(to), StandardCopyOption.REPLACE_EXISTING);
移动文件
//to若存在,将被删除,重新生成 Files.move(new File(from),new File(to));
读取文件内容(一行一行读)
List<String> strings = Files.readLines(new File(to), Charsets.UTF_8);
读取文件内容(按条件读取)
private static void guavaReadFilesProcess() throws IOException { LineProcessor<List<String>> lineProcessor = new LineProcessor<List<String>>() { List<String> list = new ArrayList<>(); @Override public boolean processLine(String s) throws IOException { System.out.println("读到内容:" + s); list.add("前缀-" + s); return true; //return false,不再读取下面内容 } @Override public List<String> getResult() { System.out.println("返回结果: "+ list); return list; } }; List<String> strings = Files.asCharSource(new File(to), Charsets.UTF_8).readLines(lineProcessor); System.out.println(strings); } /** * 读到内容:java * 读到内容:C++ * 读到内容:PHP * 返回结果: [前缀-java, 前缀-C++, 前缀-PHP] * [前缀-java, 前缀-C++, 前缀-PHP] */
计算文件hashcode (可对比两个文件是否一样)
//Hashing.md5();Hashing.sha256() HashCode hash = Files.asByteSource(new File(to)).hash(Hashing.sha512());
写文件
String path = "D:\\自定义代码\\Guava\\guava\\src\\2.txt"; File file = new File(path); Files.asCharSink(file, Charsets.UTF_8).write("hhhh"); String read = Files.asCharSource(file, Charsets.UTF_8).read(); System.out.println("读取: "+ read); //追加内容 Files.asCharSink(file, Charsets.UTF_8, FileWriteMode.APPEND).write("\nhhhh2"); String read2 = Files.asCharSource(file, Charsets.UTF_8).read(); System.out.println("读取: "+ read2);
获取某路径目录
public static void main(String[] args) { String path = "D:\\自定义代码\\Guava\\guava\\src\\main"; File file = new File(path); //获取path下子目录 Iterable<File> childrens = Files.fileTreeTraverser().children(file); for (File children : childrens) { System.out.println("子目录: " + children); } //获取path下所有目录 preOrderTraversal postOrderTraversal顺序不一样 FluentIterable<File> files = Files.fileTreeTraverser().preOrderTraversal(file); for (File file1 : files) { System.out.println("全目录: " + file1); } /** 子目录: D:\自定义代码\Guava\guava\src\main\java */
获取某路径目录(自定义过滤)
public static void main(String[] args) { String path = "D:\\自定义代码\\Guava\\guava\\src\\main"; File file = new File(path); //preOrderTraversal postOrderTraversal顺序不一样 FluentIterable<File> files = Files.fileTreeTraverser().preOrderTraversal(file).filter(new Predicate<File>() { @Override public boolean apply(@Nullable File input) { return input.isFile(); //只要文件 } }); for (File file1 : files) { System.out.println(file1); } }