實用的工具類,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));
- }