File类:文件和目录路径名的抽象表示形式。一个File对象可以代表一个文件或目录,但不是完全对应的。建立File对象不会对文件系统产生影响。(java.io.File)
user.dir:系统根据用户的工作路径来解释相对路径。
1.文件名的常用方法
getName():获取文件名。
getPath():获取路径,如果是绝对路径,则返回完整路径,否则返回相对路径。
getAbsolutePath():返回完整的绝对路径。
getParent():返回上级目录,如果是相对,返回null。
renameTo(File newName):重命名。
2.判断信息
exists():判断文件是否存在。
canWrite():判断文件是否可写。
canRead():判断文件是否可读。
isFlie():判断是否是文件。
isDirectory():判断是否是文件夹。
isAbsolute():消除平台差异,ie以盘符开头,其他以“/”开头。
3.长度
length():文件的字节数。
4.创建和删除
createNewFile():不存在则创建文件,存在则返回false。
delete():删除文件。
static createTempFlie(前缀3个字节长,后缀默认.temp):默认临时空间
static createTempFlie(前缀3个字节长,后缀默认.temp,目录)。
5.操作目录
mkdir():创建目录,必须确保父目录存在,如果不存在则创建失败。
mkdirs():创建目录,如果目录链不存在,一同创建。
list():文件|目录字符串格式。
listFiles():输出文件夹下文件。
static listRoots():输出根路径。
测试类如下:
public class Demo03 {
public static void main(String[] args) {
try {
test03();
} catch (IOException e) {
e.printStackTrace();
System.out.println("文件操作失败!");
}
}
public static void test03() throws IOException{
String path = "D:/xp/test/200";
File src = new File(path);
if (!src.exists()){
boolean flag = src.createNewFile();
System.out.println(flag ? "成功" : "失败");
}
}
public static void test02(){
String path = "D:/xp/test/2.jpg";
//String path = "D:/xp/test/200.txt";
File src = new File(path);
//是否存在
System.out.println("文件是否存在:"+ src.exists());
//是否可读
System.out.println("文件是否可读:"+ src.canRead());
//是否可写
System.out.println("文件是否可写:"+ src.canWrite());
System.out.println("文件的长度为:"+ src.length());
if (src.isFile()){
System.out.println("文件");
}else if(src.isDirectory()){
System.out.println("文件夹");
}else {
System.out.println("...");
}
}
public static void test01(){
File src = new File("2.jpg");
System.out.println(src.getName());//返回名称
System.out.println(src.getPath());//如果是绝对路径,返回完整路径,否则相对路径
System.out.println(src.getAbsolutePath());//返回绝对路径
System.out.println(src.getParent());//返回上一级目录,如果是相对路径,返回null
}
}
还有一个实现了输出子孙级目录|文件的名称功能的代码:
public class Demo05 {
public static void main(String[] args) {
String path = "D:/xp/test";
File parent = new File(path);
printName(parent);
//输出根路径:输出盘符
File[] roots = File.listRoots();
System.out.println(Arrays.toString(roots));
}
/**
* 输出路径
*/
public static void printName(File src){
if (null==src || !src.exists()){
return;
}
System.out.println(src.getAbsolutePath());
if (src.isDirectory()){
for (File sub : src.listFiles()){
printName(sub);
}
}
}
}