参考资料:《Java 技术手册》
File 类
File 类是对文件系统中文件以及文件夹进行操作的类,可以通过面向对象的思想操作文件和文件夹。是以前 Java 处理文件 I/O 的基础。这个抽象既能表示文件,也能表示目录,不过有时使用起来有些麻烦,写出的代码如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| File homedir = new File(System.getProperty("user.home"));
File f = new File(homedir, "app.conf");
if (f.exists() && f.isFile() && f.canRead()) { File configdir = new File(f, ".configdir"); configdir.mkdir(); f.renameTo(new File(configdir, ".config")); }
|
上述代码展现了 File 类使用灵活的一面,但也演示了这种抽象带来的一些问题。一般情况下,需要调用很多方法查询 File 对象才能判断这个对象到底表示的是什么,以及具有什么能力。
File 类中有相当多的方法,但根本没有直接提供一些基本功能(尤其是无法读取文件的内容),下述代码简要总结了 File 类中的方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| boolean canX = f.canExecute(); boolean canR = f.canRead(); boolean canW = f.canWrite();
boolean ok; ok = f.setReadOnly(); ok = f.setExecutable(true); ok = f.setReadable(true); ok = f.setWritable(false);
File absF = f.getAbsoluteFile(); File canF = f.getCanonicalFile(); String absName = f.getAbsolutePath(); String canName = f.getCanonicalPath(); String name = f.getName(); String pName = getParent(); URI fileURI = f.toURI();
boolean exists = f.exists(); boolean isAbs = f.isAbsolute(); boolean isDir = f.isDirectory(); boolean isFile = f.isFile(); boolean isHidden = f.isHidden(); long modTime = f.lastModified(); boolean updateOK = f.setLastModified(updateTime); long fileLen = f.length();
boolean renamed = f.renameTo(destFile); boolean deleted = f.delete();
boolean createdOK = f.createNewFile();
File tmp = File.createTempFile("my-tmp", ".tmp"); tmp.deleteOnExit();
boolean createdDir = dir.mkdir(); String[] fileNames = dir.list(); File[] files = dir.listFiles();
|