java中的File对象

Constructing File Instances

File file1 = new File("/home/myfile1.dat");//绝对路径
File file2 = new File("./myfile.dat");//相对路径

当使用相对路径时,默认是相对于JVM的启动的当前用户目录来的,可以通过java.lang.SystemgetProperty("user.dir")得到。File的实例实际上是对文件或路径的抽象表示(并不保证它代表的路径时存在的)。

由于不同系统的文件系统目录不同,因此,最好使用相对路径来处理文件读写。如果必须用绝对路径,那么为了保证跨平台,最好使用File.listRoots()方法获得根目录,该方法在_Linux_上返回一个根目录,而在_Windows_上返回每一个盘符的根目录。

Learning About Stored Abstract Paths

当你拿到一个File对象,可以获取它存储的抽象路径。

Method Description
File getAbsoluteFile() 获得具有绝对路径形式的File对象
String getAbsolutePath() 获得当前File对象的绝对路径形式(/home/jintao/./files/file.dat)
File getCanonicalFile() 获得正则路径的File对象
String getCanonicalPath() 获得正则路径 (/home/jintao/files/file.dat)
String getName()
String getParent()
File getParentFile() 若父路径不是文件夹,返回null
String getPath() 返回当前对象的抽象路径字符串
boolean isAbsolute() 是否是绝对路径

下面看看getAbsolutePath,getCanonicalPathgetPath三者的异同:

File file = new File("./file.dat");
File file1 = new File("D:/file.dat");
@Test
public void filePath() throws Exception {
  System.out.println(file.getAbsolutePath() + "\tabs path");
  System.out.println(file1.getAbsolutePath() + "\tabs path");
  System.out.println(file.getCanonicalPath() + "\tcan path");
  System.out.println(file1.getCanonicalPath() + "\tcan path");
  System.out.println(file.getPath() + "\tpath");
  System.out.println(file1.getPath() + "\tpath");
}
//output:
C:\Users\jintao\git\java-io\java-io\.\file.dat	abs path
D:\file.dat	abs path
C:\Users\jintao\git\java-io\java-io\file.dat	can path
D:\file.dat	can path
.\file.dat	path
D:\file.dat	path

getPath方法返回的路径就是File对象构造时的路径,路径在File中就是个字符串,因此,路径中会有/home/jintao/files/../folds/file2的形式,正则路径就是将里面的相对路径表示符号转换为绝对路径的形式。

Learning About a Path's File or Directory

主要方法:

Method Description
boolean exists() 判断抽象路径代表的文件或目录是否在系统中存在
boolean isDirectory() 是否是目录
boolean isFile() 是否是一个文件,而不是一个链接或目录
boolean isHidden() 是否是隐藏文件
long lastModified() 上次修改时间
long length() 文件大小(若文件不存在,返回0)

examples:

File fileExists = new File("./fileExists");
fileExists.createNewFile();
File fileNonExists = new File("./fileNonExists");

System.out.println("fileExists ? " + fileExists.exists());
System.out.println("fileNonExists ? " + fileNonExists.exists());
System.out.println("is dir? " + fileExists.isDirectory());
System.out.println("is file? " + fileExists.isFile());
System.out.println("lastModified : " + fileExists.lastModified());
System.out.println("file size: " + fileExists.length());

Listing File System Root Directories

listRoots()方法可以列出当前系统的根目录,由于_Windows_系统每个盘符代表一个根目录,所以该方法返回一个File[],在_Windows_下,返回所有盘符,而在_Linux_下,返回/目录。

Obtaining Disk Space Information

分区是操作系统特定的存储部分,作为文件系统。而在Java6之前,我们要想获得磁盘的空间信息,需要创建不同大小的文件来猜,是猜!

Method Description
long getFreeSpace() 返回该File对象指代分区的未分配字节数,若该对象并不是一个分区,则返回0
long getTotalSpace() 返回分区总的字节数
long getUsableSpace 返回可用字节数,即还能分配多少字节

examples:

File partitionD = new File("D:/");
File notPartition = new File("./f");
System.out.println("free space");
System.out.println(partitionD.getFreeSpace() + "\tpartition");
System.out.println(notPartition.getFreeSpace() + "\tnone partition");
System.out.println("total space");
System.out.println(partitionD.getTotalSpace() + "\tpartition");
System.out.println(notPartition.getTotalSpace() + "\tnone partition");
System.out.println("usable space");
System.out.println(partitionD.getUsableSpace() + "\tusable partition");
System.out.println(notPartition.getUsableSpace() + "\tnone partiton");
//output:
free space
45532418048	partition
0	none partition
total space
160039239680	partition
0	none partition
usable space
45532418048	usable partition
0	none partiton

尽管getFreeSpace()getUsableSpace()看起来相似,getUsableSpace会检查写权限和系统的其它限制,因此,它会更加精确。

注意:上面这两个方法其实返回的都不是真实的可用空间,因为JVM之外的程序会分配空间,导致实际可用的空间是比上面结果更少的。

Listing Directories

Method Description
String[] list() 返回该目录下的文件和目录名
String[] list(FilenameFilter filter) 支持文件名过滤
File[] listFiles() 返回的是File对象
File[] listFiles(FileFilter filter) 可以对文件进行过滤
File[] listFiles(FilenameFilter filter) 对文件名过滤

examples:

File dir = new File("F:/winbak");
System.out.println("just list");
String[] list = dir.list();
Stream.of(list).forEach(System.out::println);

System.out.println("using filename filter");
String[] list1 = dir.list(new FilenameFilter() {

  @Override
  public boolean accept(File dir, String name) {

    return name.endsWith("zip");
  }
});
Stream.of(list1).forEach(System.out::println);

File[] dirs = dir.listFiles(new FileFilter() {

  @Override
  public boolean accept(File pathname) {
    return pathname.isDirectory();
  }
});
System.out.println(Arrays.deepToString(dirs));

Creating/Modifying Files and Directories

Method Description
boolean createNewFile() 创建新文件或目录(如果不存在)
static File createTempFile(String prefix,String suffix) 在默认临时文件目录创建文件
static File createTempFile(String prefix, String suffix,File directory) 在制定目录创建临时文件
boolean delete() 删除文件,若是目录,目录必须为空才能顺利
void deleteOnExit() JVM退出时删除
boolean mkdir() 创建目录
boolean mkdirs() 创建抽象路径上的所有目录
boolean renameTo(File dest) 重命名,这个不是平台独立的,注意
boolean setLastModified(long time) 指定最后修改日期

examples:

File newFile = new File("./newFile");
File newTmpFile = File.createTempFile("newTmpFile", "dat");
File newLocalTmpFile = File.createTempFile("localTmp", null, new File("."));
newFile.deleteOnExit();
File noneExistingFile = new File("./none/existing/files/file.txt");
noneExistingFile.getParentFile().mkdirs();
noneExistingFile.createNewFile();
noneExistingFile.renameTo(new File("./none/existing/files/file.txt111"));

Setting and Getting Permissions

自从JDK1.2添加setReadOnly方法以来,直到java6。这期间并没有将只读文件或目录设置为可写的方法。所以,java之前的发展历程也不是那么好看吧,哈哈。

JDK6添加的方法:

Method Description
boolean setExecutable(boolean executable, boolean ownerOnly)
boolean setExecutable(boolean executable)
boolean setReadable(boolean readable, boolean ownerOnly)
boolean setReadable(boolean readable)
boolean setWritable(boolean writable, boolean ownerOnly)
boolean setWritable(boolean writable)

examples:

File per = new File("./per");
per.createNewFile();
per.setExecutable(true);
per.setReadable(true);
per.setWritable(true, true);
System.out.println("checking permissions");
System.out.println("executable? " + per.canExecute());
System.out.println("readable? " + per.canRead());
System.out.println("writable? " + per.canWrite());
//output:
checking permissions
executable? true
readable? true
writable? true

posted @ 2017-01-31 00:35  JintaoXIAO  阅读(311)  评论(0编辑  收藏  举报