File类
先写结论:File类只能对文件以及文件夹操作,但是不能对文件里面的内容进行操作。很重要不能操作文件里面的内容。
文件的路径的写法:
1." c:/file/world.txt"
2. “homework/day15/Demo.java”
3. “c:” + File.spector + “world.txt”
一共有三种写法:/就是一个;\就是两个;第三种就是File.spector和/ 以及\效果相同。
推荐使用第三种方法。因为第三种方法可以跨平台,也就是window,linux都可以识别,但是/或者\有可能识别不了。
File file1 = new File("C:\\Users\\Mould\\Desktop\\file1\\hello.docx"); //这种方法要知道
File file2 = new File("d:/hello/world.docx"); //这种方法要知道
File file3 = new File("E:"+ File.separator+ "WORD" + File.separator + "study.txt"); //推荐使用这种方法
File.exists()
表示文件是否存在。返回一个boolean
对象.list()
获取当前文件下的所有子文件夹,即只是下一级,不能获取孙文件夹下的。
写点代码,常用的方法。
File file1 = new File("C:\\Users\\Mould\\Desktop\\file1\\hello.docx");
if( file1.exists()) {
//如果文件存在就获取文件的名字
System.out.println("文件已存在");
String name = file1.getName();
System.out.println("文件名为:" + name);
}else {
//文件不存在,就打印文件路径
System.out.println("文件不存在");
File parent = file1.getParentFile();
System.out.println("文件的路径为:" + parent);
String name = file1.getName();
System.out.println("文件名为:" + name);
boolean res1 = file1.canExecute();
System.out.println("文件可操作吗:" + res1);
boolean res2 = file1.canRead();
System.out.println("文件可读吗:" + res2);
boolean res3 = file1.canWrite();
System.out.println("文件可写吗:" + res3);
boolean dir = file1.isDirectory();
System.out.println("file1是文件吗:" + dir);
String path = file1.getPath();
System.out.println("file1的路径:" + path);
}