File类
1 凡是输入、输出的类,接口都在java.io下
2 File是一个类,可由构造器创建其对象。此对象对应一个文件或目录。分为:绝对路径和相对路径
3 File类对象与平台无关的
4 File中的方法,仅涉及到如何创建、删除、重命名等等。只要涉及文件内容,File方法无能为力,只能用io流决定
5 File类的对象常作为io留的具体类的构造器的形参
package lianxi1; import java.io.File; import java.io.IOException; import java.util.Date; import org.junit.Test; public class TestFile { @Test //访问文件 public void Test1(){ //File对象对应一个文件或目录,分为绝对路径和相对路径 File file1 = new File("d:/io/helloworld.txt"); //或者(“d:\\io\\helloworld.txt") File file2 = new File("d:\\io\\io1"); File file3 = new File("Goodbye2"); System.out.println(file1.getName()); System.out.println(file1.getPath()); System.out.println(file1.getAbsolutePath()); System.out.println(file1.getParent()); System.out.println(file1.getAbsoluteFile()); System.out.println(file3.getName()); System.out.println(file3.getPath()); System.out.println(file3.getAbsolutePath()); System.out.println(file3.getParent()); System.out.println(file3.getAbsoluteFile()); //file1.renameTo(file2)要求file1一定存在,file2一定不存在 boolean t = file1.renameTo(file3); System.out.println(t); } @Test //文件检测 public void Test2(){ File file2 = new File("d:\\io\\io1"); System.out.println(file2.exists()); System.out.println(file2.canRead()); System.out.println(file2.canWrite()); System.out.println(file2.canExecute()); System.out.println(file2.isDirectory()); System.out.println(new Date(file2.lastModified())); System.out.println(file2.length()); } @Test //文件和目录操作 public void Test3() throws IOException{ File file1 = new File("d:/io/helloworld.txt"); System.out.println(file1.delete()); //true if(!file1.exists()){ System.out.println(file1.createNewFile()); //true } File file2 = new File("d:\\io3\\io2"); if(!file2.exists()){ System.out.println(file2.mkdir()); //false System.out.println(file2.mkdirs()); //true } File file3 = new File("d:\\"); String[] strs = file3.list(); for(String s1:strs){ System.out.println(s1); } System.out.println(); File file4 = new File("d:\\"); File[] strs2 = file3.listFiles(); for(File s2:strs2){ System.out.println(new Date(s2.lastModified())); } } }
浙公网安备 33010602011771号