通过File类可获取文件的信息或进行文件的复制、删除、重命名等管理操作,目录管理也由File实现。
1. 创建文件对象
- File(String path) 例:File myFile = new File(“/etc/motd”);
- File(String path,String name) 例:File myFile = new File(“/etc”,”motd”);
- File(File dir,String name) 例1:File f1 = new File(“c:\abc”);
例2:File f2 = new File(f1, “3.txt”); //c:\abc\3.txt
2. 获取文件或目录属性
- String getName() 返回文件名
- String getPath() 返回文件路径
- String getAbsolutePath() 返回文件绝对路径
- String getParent() 返回父目录
- boolean exists() 判断文件是否存在
- boolean canWrite() 判断文件是否可写
- boolean canRead()判断文件是否可读
- boolean isFile()判断是否为文件
- boolean isDirectory() 判断是否为目录
- long lastModified() 文件的最后修改时间
-
3.文件或目录操作
boolean renameTo(File newName)
- boolean mkdir() 在当前目录下创建xyz子目录,例:File d=new File(“xyz”); d.mkdir();
- String[ ] list()
- File[ ] listFiles()
- void delete()
- boolean equals(File f)
```java import java.io.*; class test13_4{ public static void main(String args[]) {import java.io.*;
class test13_4{
static File fileToCheck;
public static void main(String[] args) throws IOException {
for (int i=0;i<args.length;i++)
{
fileToCheck = new File(args[i]);
info(fileToCheck); //调用方法输出指定文件信息info(new File(args[i]))
}
}
public static void info (File f) throws IOException {
System.out.println("Name: "+f.getName());
System.out.println("Path: "+f.getPath());
System.out.println("Absolute Path: "+f.getAbsolutePath());
if (f.exists())
{
System.out.println("File exists.");
System.out.println( "and is Readable : "+f.canRead());
System.out.println("and is Writeable: "+f.canWrite());
System.out.println("File is " + f.length()+" bytes."); //File is 4458 bytes.求文件长度
}
else
System.out.println("File does not exist.");
}
}
} }File file=new File("D:\\学习代码");
if(!file.exists())
{
System.out.println("dirctory is empty");
return;
}
File[] fileList=file.listFiles();
for(int i=0;i<fileList.length;i++)
{
if(fileList[i].isDirectory())
System.out.println("dirctory is :"+fileList[i].getName()); //文件夹
else
System.out.println("file is :"+fileList[i].getName()); //文件
}
运行结果: dirctory is :algorithm-problem-brushing dirctory is :a的n次方 dirctory is :java-learning file is :java.txt dirctory is :MatLab学习 dirctory is :practice ```