File类文件路径详解

1.文件的绝对路径

package firstExam.fourth;

import java.io.File;

/*
* File类包含许多获取文件属性的方法,以及重命名和删除文件和目录的方法,
* 但是File类不包含读写文件内容的方法。
* 可以使用new File(“CopyFile.java”);为在当前目录下(工程的一级子目录)
* 的文件CopyFile.java创建一个File类对象,前提是SourceFile.java文件存在,
* 并且任何需要读取(输入)的文件都必须存在,否则会出现FillNotFoundException
* 创建对象的目的是为了获取File类的一些属性和方法
*/

public class MyTestFile3 {

public static void main(String[] args) {
    //SourceFile.java文件的绝对路径
    File file=new File("E:\\workspace\\allExams\\src\\firstExam\\fourth\\SourceFile.java");
    System.out.println("is file exit?"+file.exists());
    System.out.println("is file?"+file.isFile());
}

}
运行结果

2.文件的相对路径
package firstExam.fourth;

import java.io.File;

public class MyTestFile1 {

public static void main(String[]args){
    //此处src是工程allExample的一级子目录,/或者\\皆可
    File file=new File("src/firstExam/fourth/SourceFile.java");
    System.out.println("is file exit?"+file.exists());
    System.out.println("is file?"+file.isFile());
    System.out.println("nihao ");
}

}

3.错误写法
package firstExam.fourth;

import java.io.File;

public class MyTestFile2 {

public static void main(String[] args) {
    //firstExam是工程的二级子目录,出错
    File file=new File("firstExam\\fourth\\SourceFile.java");
    System.out.println("is file exit?"+file.exists());
    System.out.println("is file?"+file.isFile());
    System.out.println("nihao ");

}

}

猜你喜欢

转载自blog.csdn.net/qq_38986609/article/details/78488678