系统的路径分隔符
1 | String separator = FileSystems.getDefault().getSeparator(); |
耗时计算
1 | long startTime=System.currentTimeMillis(); |
按字节写文件
1 | //读取配置文件,获取文件上传路径 |
文件夹拷贝
Files工具类中有个walkFileTree用来遍历文件1
2
3
4
5
6
7
8
9
public static Path walkFileTree(Path start, FileVisitor<? super Path> visitor)
throws IOException
{
return walkFileTree(start,
EnumSet.noneOf(FileVisitOption.class),
Integer.MAX_VALUE,
visitor);
}
看上面注释得出start参数是要遍历文件的位置,visitor则是一个接口规定了遍历文件将要做的事情
而visitor有4个方法:
- 访问文件前preVisitDirectory
- 访问文件visitFile时
- 访问文件失败时
- 访问文件后visitFileFailed
因此在visitor考虑实现文件的拷贝,在构造visitor类时将拷贝输出的路径传入
1 | public class CopyFileTree extends SimpleFileVisitor<Path>{ |
文件夹压缩
FileOutputStream 将数据写入文件的输出流,用于写入原始字节流如图像数据。 要编写字符流,请考虑使用。
ZipOutputStream 压缩文件并生成压缩文件。
1 | private static void doZipFile(File fileToZip, String fileName, ZipOutputStream zipOut) throws IOException { |
文件压缩目前只能通过递归来压缩了,这里要注意的就是递归的结束条件不要陷入死循环了
遇见的错误
Input length = 1
编码不是UTF-8却按UTF-8读取了
Files.readAllLines(filePath, StandardCharsets.UTF_8)
如果要继续深入了解的文件的操作可以继续研究NIO。