1

Given the absolute path as a variable String pathname, how can I do the following using the Java Class File? The answers as far as I know are in parenthesis, please confirm.

  1. get the size of the file/directory? (I'm not sure)

  2. test if the absolute path even leads to something that exists? (File.exists(pathname), which should return a boolean true if it exists, boolean false otherwise)

  3. see if this is this a file or directory? (File.isFile(pathname), which returns a boolean true if the pathname leads to a file, false otherwise. file.isDirectory(pathname), which returns a boolean true if the pathname leads to a directory, false otherwise)

  4. see the last date modified? (File.lastModified(pathname), which returns a long number which I already have the method for to convert to a specific date

A related but separate question: is there something that is a "file", like a .doc, .jpeg, .mpeg, .mp3, .xml, .* that will fail both isFile and isDirectory tests? If so, how can I distinguish between an empty folder and a folder with a file that fails both isFile and isDirectory tests? I'm asking because on the File class documentation, it states the following for isFile: Tests whether the file denoted by this abstract pathname is a normal file. A file is normal if it is not a directory and, in addition, satisfies other system-dependent criteria. Any non-directory file created by a Java application is guaranteed to be a normal file.

4

2 回答 2

5
File f = new File(path);
// Get size of file (not a directory though)
f.length();
// Check if file exists
f.exists();
// Check if file is directory
f.isDirectory();
// Check if file is file
f.isFile();
// Last modified date
f.lastModified();

参考:java.io.File 的 JavaDoc

如果您想要目录的大小,则必须在遍历要为其计算大小的目录时组合这些方法,或者您可以使用像Apache Commons IO中的第三方库FileUtils,它有一个显然可以处理的方法目录的大小也是如此。sizeOf

于 2013-05-04T05:59:27.420 回答
0

是否存在某种“文件”,例如 .doc、.jpeg、.mpeg、.mp3、.xml、.* 会导致 isFile 和 isDirectory 测试失败?

不,这些都是常规文件。如果它是一个文件,它将通过isFile测试。

不是“普通文件”或目录的东西是设备文件和命名管道文件。java.io.File无法准确地区分这些……或符号链接。

如果您希望能够执行特定于操作系统的操作,请查看 Java 7 的java.nio.file包,特别是Files该类。

于 2013-05-04T06:11:21.377 回答