文章目录
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.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]
*/
//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("
hhhh2");
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:自定义代码Guavaguavasrcmainjava
*/
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);
}
}