文章目录
一、File 类的使用
1.常用构造器
构造器测试:
@Test
public void test1(){
//构造器1
File file1 = new File("hello.txt"); //相对于当前module
File file2 = new File("D:\\workspace_idea1\\JavaSenior\\day08\\he.txt"); //绝对路径
System.out.println("file1l==>"+file1.getAbsoluteFile());
System.out.println("file12==>"+file2);
//构造器2:
File file3 = new File("D:\\workspace_idea1","JavaSenior");
System.out.println("file13==>"+file3);
//构造器3:
File file4 = new File(file3,"hi.txt");
System.out.println("file14==>"+file4);
}
测试结果:
2.路径分隔符
separator
测试:
@Test
public void yrxTest1(){
File file1 = new File("D:\\info.text");
File file2=new File("D:"+File.separator+"yrx"+File.separator+"info.txt");
File file3=new File("D:/yrx");
System.out.println(file1);
System.out.println(file2);
System.out.println(file3);
}
测试结果:当前系统为Windows
需要注意一下:在main方法中使用相对路径是相对于当前project
public class FileTest {
public static void main(String[] args) {
File file1 = new File("hello.txt");//相对于当前project
System.out.println(file1.getAbsoluteFile());
}
}
测试结果:
如果在单元测试里使用相对路径是相对于当前moudle
@Test
public void test1(){
//构造器1
File file1 = new File("hello.txt");//相对于当前module
System.out.println("file1l路径"+file1.getAbsoluteFile());
}
测试结果:
3.常用方法
获取功能测试:
@Test
public void test2(){
File file1 = new File("hello.txt"); //文件内容为helloworld
File file2 = new File("d:\\FileTest\\hi.txt"); //文件内容为Hello World
System.out.println(file1.getAbsolutePath());
System.out.println(file1.getPath());
System.out.println(file1.getName());
System.out.println(file1.getParent());
System.out.println(file1.length());
System.out.println(new Date(file1.lastModified()));
System.out.println();
System.out.println(file2.getAbsolutePath());
System.out.println(file2.getPath());
System.out.println(file2.getName());
System.out.println(file2.getParent());
System.out.println(file2.length());
System.out.println(file2.lastModified());
}
测试结果:
list()和listFiles()测试:
@Test
public void test3(){
File file = new File("d:\\FileTest"); //这里必须是目录,且该目录下必须要有文件,否则报空指针异常
String[] list = file.list();
for(String s : list){
System.out.println(s);
}
System.out.println();
File[] files = file.listFiles();
for(File f : files){
System.out.println(f);
}
}
测试结果:
创建或删除文件测试
@Test
public void test6() throws IOException {
File file1