Java文件类以抽象的方式代表文件名和目录路径名。该类主要用于文件和目录的创建、文件的查找和文件的删除等。
File对象代表磁盘中实际存在的文件和目录。通过以下构造方法创建一个File对象。
1.通过给定的父抽象路径名和子路径名字符串创建一个新的File实例。
File(File parent, String child);
2.通过将给定路径名字符串转换成抽象路径名来创建一个新 File 实例。
File(String pathname)
3.根据 parent 路径名字符串和 child 路径名字符串创建一个新 File 实例。
File(String parent, String child)
4.通过将给定的 file: URI 转换成一个抽象路径名来创建一个新的 File 实例。
File(URI uri)
创建File对象成功后,可以使用以下列表中的方法操作文件。
序号 | 方法描述 |
1 | public String getName() |
2 | public String getParent()、 |
3 | public File getParentFile() |
4 | public String getPath() |
5 | public boolean isAbsolute() |
6 | public String getAbsolutePath() |
7 | public boolean canRead() |
8 | public boolean canWrite() |
9 | public boolean exists() |
10 | public boolean isDirectory() |
11 | public boolean isFile() |
12 | public long lastModified() |
13 | public long length() |
14 | public boolean createNewFile() throws IOException |
15 | public boolean delete() |
16 | public void deleteOnExit() |
17 | public String[] list() |
18 | public String[] list(FilenameFilter filter) |
19 | public File[] listFiles() |
20 | public File[] listFiles(FileFilter filter) |
21 | public boolean mkdir() |
22 | public boolean mkdirs() |
23 | public boolean renameTo(File dest) |
24 | public boolean setLastModified(long time) |
25 | public boolean setReadOnly() |
26 | public static File createTempFile(String prefix, String suffix, File directory) throws IOException |
27 | public static File createTempFile(String prefix, String suffix) throws IOException |
28 | public int compareTo(File pathname) |
29 | public int compareTo(Object o) |
30 | public boolean equals(Object obj) |
31 | public String toString() |
实例
下面的实例演示了File对象的使用:
实例
import java.io.File;
public class Main {
public static void main(String args[]) {
String dirname = "/java";
File f1 = new File(dirname);
if (f1.isDirectory()) {
System.out.println("Directory of " + dirname);
String s[] = f1.list();
for (int i = 0; i < s.length; i++) {
File f = new File(dirname + "/" + s[i]);
if (f.isDirectory()) {
System.out.println(s[i] + " is a directory");
} else {
System.out.println(s[i] + " is a file");
}
}
} else {
System.out.println(dirname + " is not a directory");
}
}
}
以上实例编译运行结果如下:
Directory of /java
bin is a directory
lib is a directory
demo is a directory
test.txt is a file
README is a file
index.html is a file
include is a directory
标签:Java,String,boolean,抽象,路径名,File,目录 From: https://blog.51cto.com/u_14932227/6042474