实用的工具类,Path,Paths,Files,FileSystem
有一些很灵活的处理方法:
- //得到一个Path对象
- Path path = Paths.get("/test/a.txt");
- //Path转换File
- File file = path.toFile();
- Files.readAllBytes(path);
- Files.deleteIfExists(path);
- Files.size(path);
正确拼接路径不要手动拼接路径
不好的代码:
- String game = "foo";
- File file = new File("~/test/" + game + ".txt");
- System.out.println(File.pathSeparator);
- System.out.println(File.separator);
- Path path = Paths.get("~/test/", "foo", "bar", "a.txt");
- System.out.println(path);
- // ~/test/foo/bar/a.txt
读取文件的所有内容,文件的所有行
读取文件所有内容前,先判断文件大小,防止OOM。
- public static byte[] readAllBytes(String fileName, long maxSize) throws IOException {
- Path path = Paths.get(fileName);
- long size = Files.size(path);
- if (size > maxSize) {
- throw new IOException("file: " + path + ", size:" + size + "> " + maxSize);
- }
- return Files.readAllBytes(path);
- }
- public static List<String> readAlllines(String fileName, Charset charset, long maxSize) throws IOException {
- Path path = Paths.get(fileName);
- long size = Files.size(path);
- if (size > maxSize) {
- throw new IOException("file: " + path + ", size:" + size + "> " + maxSize);
- }
- return Files.readAllLines(path, charset);
- }
利用JDK7的特性,auto close,远离一堆的catch, close
- Path path = Paths.get("~/test/", "foo", "bar", "a.txt");
- try (InputStream in = Files.newInputStream(path)) {
- // process
- //in.read();
- }
历遍目录
DK7新特性,FileVisitor
- public class MyFileVisitor extends SimpleFileVisitor<Path>{
- @Override
- public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
- System.out.println(file);
- return FileVisitResult.CONTINUE;
- }
- public static void main(String[] args) throws IOException {
- Path path = Paths.get("/home/user/test");
- Files.walkFileTree(path, new MyFileVisitor());
- }
- }
判断文件是否在父路径下
网上流传一种递归判断parent的方式,http://stackoverflow.com/questions/18227634/check-if-file-is-in-subdirectory
但是查阅jdk代码后,发现getParent()函数是通过处理文件名得到的。所以直接比较文件前缀即可。
请务必注意,file.getCanonicalPath()函数 。
- public static boolean isSubFile(File parent, File child) throws IOException {
- return child.getCanonicalPath().startsWith(parent.getCanonicalPath());
- }
- public static boolean isSubFile(String parent, String child) throws IOException {
- return isSubFile(new File(parent), new File(child));
- }