Files
1.copy
可复制文本文件、图像文件
使用:
try(FileOutputStream fileOutputStream = new FileOutputStream(new File(".\\neRWtext.txt"))) {
System.out.println(Files.exists(Paths.get(".\\neRWtext.txt")));
// 如果不存在,输出流会自己新建出目标文件
Files.copy(Paths.get(".\\RWtext.txt"),fileOutputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
源码:返回值为 long ,读取的文件字节大小
public static long copy(Path source, OutputStream out) throws IOException {
// ensure not null before opening file
Objects.requireNonNull(out);
try (InputStream in = newInputStream(source)) {
return copy(in, out);
}
}
2.delete
删除文件,delete 不可以删除不存在的文件..报错. ---> 可以使用 deleteIfExists文件
使用:
Files.delete(Paths.get(".\\tt.txt"));
System.out.println(Files.deleteIfExists(Paths.get(".\\tt.txt")));
源码:返回类型为void
public static void delete(Path path) throws IOException {
provider(path).delete(path);
}
:返回值为boolean
public static boolean deleteIfExists(Path path) throws IOException {
return provider(path).deleteIfExists(path);
}
3.size
获取文件的字节数
使用:
Path path = Paths.get(".\\RWtext.txt");
System.out.println(Files.size(path));
File file = new File(".\\RWtext.txt");
System.out.println(file.length());
源码: 返回值为 long
public static long size(Path path) throws IOException {
return readAttributes(path, BasicFileAttributes.class).size();
}
: 返回值为 length
public long length() {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkRead(path);
}
if (isInvalid()) {
return 0L;
}
return fs.getLength(this);
}
4.getLastModifiedTime、getOwner、isWritable、getFileStore、probeContentType
获取文件最后修改时间&
Files常用函数笔记
最新推荐文章于 2024-05-23 17:54:58 发布