自我学习记录1--nio的文件操作
2018-04-13 15:22
363 查看
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
1.获取文件的编码格式
2.检查文件是否存在
3.touch a new file
4.find a file
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
1.获取文件的编码格式
public static Charset getCS(String FilesName) { Charset cs = null; try { InputStream inputStream = new FileInputStream(FilesName); byte[] head = new byte[3]; inputStream.read(head); inputStream.close(); if (head[0] == -17 && head[1] == -69 && head[2] == -65) { cs = StandardCharsets.UTF_8; } cs = StandardCharsets.ISO_8859_1; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return cs; }
2.检查文件是否存在
public static boolean exitsFile(String filePath,String fileName){ Path dir = Paths.get(filePath); Path path = null; try(DirectoryStream<Path> stream = Files.newDirectoryStream(dir,fileName)){ for(Path p:stream){ path = p.getFileName(); } } catch (IOException e) { e.printStackTrace(); } return (path != null); }
3.touch a new file
public static void touch(String fileName,String filePath) throws IOException { boolean flag = exitsFile(filePath, fileName); Path path = Paths.get(filePath + fileName); if (flag) { Files.delete(path); } Files.createFile(path); }
4.find a file
public static void findInAllDir(String rootPath) { Path path = Paths.get(rootPath); try { Files.walkFileTree(path, new FileVisitTree()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static class FileVisitTree extends SimpleFileVisitor<Path> { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes arg1) { if (file.toString().contains("[keyWord]")) { //do something with the file } return FileVisitResult.CONTINUE; } }
相关文章推荐
- Smart210学习记录-------文件操作
- GDI+ 学习记录(30): MetaFile 文件操作
- GDI+ 学习记录(30) MetaFile 文件操作
- Linux学习记录--文件IO操作相关系统编程
- Linux 学习记录 一(安装、基本文件操作).
- Linux学习记录--文件IO操作相关系统编程
- Linux学习记录--文件系统简单操作
- Linux学习记录--文件IO操作相关系统编程
- python 学习记录(3)—文件操作
- Linux学习记录--文件系统简单操作
- 学习记录-Qt文件的读写和删除等操作
- (转载)Linux 学习记录 一(安装、基本文件操作)
- python文件操作+字符串操作 总结(学习记录)
- 个人学习代码保存:例10.通过模板创建静态页面的操作文件的一个自定函数
- Linux命令学习(五):文件操作命令(2)
- Windows API 函数学习(7)---文件操作示例
- 孙鑫VC学习笔记:第十二讲 (四) 用API函数、CFile类操作文件
- .net 文件操作的一点记录
- Windows API 函数学习(6)---文件操作
- java Web项目中,利用其过滤功能,实现访问者每次访问服务器时,记录访问者的IP,访问时间,Url等信息,并保存到文件的操作