Java:File与Files 0、说明
File:⽤于操作⽂件、⽬录的类。
Files:提供了许多静态⽅法⽤于操作⽂件、⽬录的类。
Files中全都是静态⽅法,只在本⽂第五节对这些⽅法加以说明,其他节都是File相关内容。
1、模块:java.io.File、java.nio.File.Files
2、字段:⽤法
全是static修饰符,即静态字段,直接通过类名File访问
mkdirs方法
字段说明
String pathSeparator 路径分隔符,String形式,Win10中是";"
这⾥的路径是指类似环境变量中的不同Path之间的分隔符
char pathSeparatorChar
路径分隔符,char形式,Win10中是';'
注意与String形式的区别——引号
String separator路径中的⽂件分隔符,String形式,Win10中是"\"
char separatorChar路径中的⽂件分隔符,char形式,Win10中是'\'
3、构造⽅法
构造⽅法说明
File(File parent , String child)构造parent+child指定的⽂件对象
File(String pathname)构造pathname指定路径的⽂件对象
File(String parent , String child)构造parent+child指定的⽂件对象
File(URI uri)构造URI指定的⽂件对象
File对象可以表⽰⽂件与⽬录,构造File时,即使传⼊的⽂件⽬录不存在也不会出错,因为单纯的构造并不会导致任何磁盘操作,只有当我们调⽤File的某些⽅法时,才真正进⾏磁盘操作。
4、路径
构造File时,可以传⼊绝对路径和相对路径,Windows平台⽤\作为⽂件分隔符,在Java字符串要⽤\\表⽰⼀个\。Linux平台使⽤/作为路径分隔符。
传⼊相对路径时,是相对于当前⽬录,也就是说当前⽬录+相对路径=绝对路径:
//假设当前⽬录是 C:\Docs
File f1 = new File("sub\\javac"); // 绝对路径是C:\Docs\sub\javac
File f3 = new File(".\\sub\\javac"); // 绝对路径是C:\Docs\sub\javac
File f3 = new File("..\\sub\\javac"); // 绝对路径是C:\sub\javac
⼀个点.表⽰当前⽬录,两个点..表⽰⽗⽬录。
3种路径
getPath()构造时传⼊的路径
getAbsolutePath()绝对路径
getCanonicalPath()规范路径
绝对路径:可能包含..与.的绝对路径;
规范路径:不包含..与.的绝对路径。
5、File静态⽅法:⽤法( ... )
返回值
类型
⽅法说明
File createTempFile(String prefix ,
String suffix)
在默认temporary-file⽬录下,⽤指定
前后缀构造⼀个空⽂件
File createTempFile(String prefix ,
String suffix , File directory)
在指定⽬录(参数directory)下,⽤指
定前后缀构造⼀个空⽂件
File[ ]listRoots()列出可⽤的⽂件系统的roots
5.5、Files静态⽅法:⽤法( ... )
返回值类型⽅法说明
long copy(InputStream in , Path target ,
options)
从⼀个InputStream中
复制全部bytes到⽂件
long copy(Path source,OutputStream out)复制⼀个⽂件中的所有bytes到OutputStream 中
Path copy(Path source , Path target , options)复制source到target处Path createDirectories(Path dir , FileAttribute<?>... attrs)创建⼀个空⽬录
Path createFile(Path dir ,FileAttribute<?> ... attrs)创建⼀个空⽂件
Path createLink(Path link , Path existing)为⼀个存在的⽂件构造
link
Path
createSymbolicLink
(Path link, Path target, FileAttribute<?>... attrs)
为⼀个⽂件构造
symbolic link
Path createTempDirectory(String prefix, FileAttribute<?
>... attrs)⽤给定前缀在默认临时⽂件夹中创建⼀个新⽬录
Path
createTempDirectory
(Path dir, String prefix, FileAttribute<?>... attrs)
在给定⽬录中创建⼀个
新⽬录
Path
createTempFile
(String prefix, String suffix, FileAttribute<?>... attrs)
⽤给定前缀在默认临时
⽂件夹中创建⼀个新⽂
Path
createTempFile
(Path dir, String prefix, String suffix, FileAttribute<?
>... attrs)
在给定⽬录中创建⼀个
新⽂件
void delete(Path path)删除⽂件
boolean deleteIfExists(Path path)如果⽂件存在就删除⽂
boolean exists(Path path, options)检查⽂件是否存在
Stream<Path>
find(Path start, int maxDepth, BiPredicate<Path, BasicFileAttributes> matcher, options)
返回搜索⽂件时,⽂件
树上的Path构成的
Stream
Object
getAttribute
(Path path, String attribute, options)获取⽂件参数的值
V
getFileAttributeView
(Path path, Class<V> type, options)
获取指定类型的⽂件参
数的值
FileStore getFileStore(Path path)返回file所在的
FileStore
FileTime getLastModifiedTime(Path path, options)返回⽂件最近修改时间UserPrincipal getOwner(Path path, options)返回⽂件所有者
Set<PosixFilePermission>
getPosixFilePermissions
(Path path, options)返回⽂件的POSIX权限isDirectory(Path path, options)
isExecutable(Path path)
⽂件是否是⽬录
是否可执⾏
boolean
isHidden(Path path)
isReadable(Path path)
isRegularFile(Path path, options)
isSameFile(Path path, Path path2)
isSymbolicLink(Path path)
isWritable(Path path)
是否是隐藏⽂件
是否可读
是否是规则⽂件
是否同⼀个⽂件
是否Sym link
是否可写
Stream<String> Stream<String>
lines(Path path)
lines(Path path, Charset cs)
读取⽂件所有⾏为⼀个
Stream
Stream<Path>list(Path dir)以Stream的形式列出
dir下的所有元素
long mismatch(Path path, Path path2)返回两个⽂件第⼀个不匹配的点,如果没有则返回-1L
Path move(Path source, Path target, options)移动/重命名⼀个⽂件
BufferedReader
newBufferedReader(Path path)
newBufferedReader(Path path, Charset cs)
打开⽂件⽤以读取,返
回它的BufferReader
BufferedWriter
newBufferedWriter
(Path path, Charset cs, options)
newBufferedWriter(Path path, options)
打开或创造⼀个⽂件⽤
于写⼊,返回它的
BufferWriter
SeekableByteChannel
newByteChannel(Path path, options)
newByteChannel(Path path, Set<?
extends OpenOption> options, FileAttribute<?>... attrs)
打开或创造⼀个⽂件⽤
于访问,返回
SeekableByteChannel
DirectoryStream<Path>
newDirectoryStream(Path dir)
newDirectoryStream(Path dir, String glob)
newDirectoryStream(Path dir, DirectoryStream.Filter<?
super Path> filter)
打开⼀个⽬录,返回⼀
个DirectoryStream⽤
于迭代该⽬录下的所有
元素
InputStream newInputStream(Path path, options)打开⼀个⽂件,返回
InputStream⽤于Read
OutputStream newOutputStream(Path path, options)打开/创建⼀个⽂件,返回OutputStream⽤于Write
boolean notExists(Path path, options)检查⽂件是否不存在
String
probeContentType(Path path)检查⽂件的内容类型
byte[ ]readAllBytes(Path path)读取⽂件中的内容保存
为byte[ ]
List<String>
readAllLines(Path path)
readAllLines(Path path, Charset cs)
读取⽂件中的所有⾏,
每⾏作为String List中
的⼀个String
A
Map<String,Object>
readAttributes
(Path path, Class<A> type, options)
readAttributes
(Path path, String attributes, options)
读取⽂件参数⽤于bulk
操作
读取⽂件参数集合⽤于
bulk操作
String
readString(Path path)
readString(Path path, Charset cs)
读取⽂件中所有内容到
String中,默认解码⽅
式为UTF-8(在第⼆个
⽅法中可以指定)
Path
readSymbolicLink(Path link)读取link的Symbolic link
Path
setAttribute
(Path path, String attribute, Object value, options)
setLastModifiedTime(Path path, FileTime time)
设置、更新⽂件相关信
setOwner(Path path, UserPrincipal owner)
setPosixFilePermissions
(Path path, Set<PosixFilePermission> perms)设置、更新⽂件相关信
long size(Path path)返回⽂件⼤⼩
(bytes)
Stream<Path>walk(Path start, int maxDepth, options)
walk(Path start, options)
返回Stream,⽤于遍历
start以下的所有⽂件和
⽬录
Path walkFileTree(Path start, FileVisitor<? super Path> visitor)
walkFileTree(Path start, Set<FileVisitOption> options,
int maxDepth, FileVisitor<? super Path> visitor)
遍历⽂件树
Path
write(Path path, byte[] bytes, options)
write(Path path, Iterable<?
extends CharSequence> lines, Charset cs, options)
write(Path path, Iterable<?
extends CharSequence> lines, options)
向⽂件中写⼊bytes
向⽂件中按⾏写⼊text
Path
writeString
(Path path, CharSequence csq, Charset cs, options)
writeString(Path path, CharSequence csq, options)
向⽂件中写⼊
CharSequence(字符
序列)
Files中提供的读写⽅法,受内存限制,只能读写⼩⽂件如配置⽂件等,不能⼀次读⼊⼏个G的⼤⽂件。读写⼤型⽂件仍然要使⽤⽂件流,每次只读写⼀部分⽂件内容。
6、实例⽅法:⽤法( ... ),file是File类对象
返回值
类型
⽅法说明
boolean canExecute()检查该⽂件是否可执⾏
boolean canRead()检查该⽂件是否可Read
boolean canWrite()检查该⽂件是否可Write
int compareTo(File
pathname)检查两个路径是否相同
boolean createNewFile()如果构造File的路径不存在同名⽂件,就构造⼀
个新的、空的⽂件
boolean delete()删除⽂件/⽬录
void deleteOnExit()程序运⾏结束时删除⽂件
boolean equals(Object obj)检查该File是否与obj相等
boolean exists()检查⽂件是否存在
File getAbsoluteFile()得到该File的绝对File对象
String getAbsolutePath()得到该File的绝对路径
File getCanonicalFile()规范File对象
String getCanonicalPath()规范路径
long getFreeSpace()得到该File中的剩余空间(bytes)
String getName()得到⽂件名
String getParent()得到⽗⽬录
File getParentFile()得到⽗⽬录对应的File对象
String getPath()得到构造⽅法传⼊的路径
long getTotalSpace()得到该File的总空间(bytes)
long getUsableSpace()得到该File的可⽤空间(bytes)
int hashCode()得到该File的hash code
boolean isAbsolute()检测该File路径是否是绝对路径boolean isDirectory()检查该File是否是⽬录
boolean isFile()检查该File是否是⽂件
boolean isHidden()检查该File是否被隐藏
long lastModified()上次修改时间戳
long length()返回该File的长度(⽂件实际⼤⼩ bytes)String[ ]list()返回该⽬录中的⽂件名
String[ ]list(FilenameFilter
filter)筛选返回该⽬录中符合条件的⽂件名
File[ ]listFiles()
返回上述两个⽅法的File类型File[ ]listFiles(FilenameFilter filter)
boolean mkdir()创建⼀个空⽬录
boolean mkdirs()创建⼀个空⽬录,如果⽗⽬录不存
在就同样创建
boolean renameTo(File dest)重命名该⽂件/⽬录
boolean setExecutable(boolean executable)设置权限(只针对owner)
boolean setExecutable(boolean executable ,
boolean ownerOnly)
设置权限(对owner及
everybody)
boolean setLastModified(long time)修改最近修改时间boolean setReadable(boolean readable)设置owner的读取权限
boolean setReadable(boolean readable ,
boolean ownerOnly)
设置owner或everybody的读取权
boolean setReadOnly()设为只读⽂件boolean setWritable(boolean writable)设置owner的写⼊权限
boolean setWritable(boolean writable , boolean
ownerOnly)
设置owner或everybody的写⼊权
Path toPath()返回该⽂件的java.nio.file.Path对
String toString()返回路径
URI toURI()构造⼀个file : URI
7、具体⽅法
最常⽤
获取File对应的String:f.toString()
7.1、⽂件与⽬录
⽤isFile()、isDirectory()⽅法,可以判断该File是否是⼀个存在的⽂件、⽬录。7.2、权限和⼤⼩
boolean canRead():是否可读;
boolean canWrite():是否可写;
boolean canExecute():是否可执⾏;
long length():⽂件字节⼤⼩。
对于⽬录来说,可否执⾏表⽰能否列出它包含的⽂件和⽬录。
7.3、创建、删除
7.3.1、⽂件
当File表⽰⼀个⽂件时,通过createNewFile()创建新⽂件,delete()删除该⽂件:
File file = new File("/path/to/file");
ateNewFile()){
//创建成功
.
..
if(file.delete()){
//删除成功
}
}