項目目錄如下:
test1.class中讀取test.txt
import java.io.*; import java.util.Scanner; public class Test1 { public static void main(String[] args) throws IOException { Scanner in=new Scanner(System.in); // String path=this.getClass().getClassLoader().getResource("/"); System.out.println(System.getProperty("user.dir")); // 注意,路徑應為文件在工程中的相對路徑 File f=new File("src/test.txt"); System.out.println("......."); System.out.println(f.getPath()); System.out.println(f.getAbsolutePath()); System.out.println(f.getCanonicalPath()); BufferedReader reader=new BufferedReader(new FileReader(f)); String temp=null; int line=1; while((temp=reader.readLine())!=null){ System.out.println("line"+line+":"+temp); line++; } } }
結果如下:
總結讀取文件:
直接
// 注意,路徑應為文件在工程中的相對路徑
File f=new File("src/test.txt");
總結獲取當前路徑:
this.getClass().getClassLoader().getResource()
或
this.getClass().getClassLoader().getResources()
需要非靜態函數中使用(main函數中不能使用)
System.getProperty("user.dir")
獲取的是工程的根目錄
f.getPath()
獲取的是創建file對象時構造參數里填的值
f.getCanonicalPath()
獲取的是文件絕對路徑
f.getAbsolutePath()
獲取的也是文件的絕對路徑,但是不會解析.和..
參考:
https://www.cnblogs.com/franson-2016/p/5728280.html
https://www.cnblogs.com/xuyatao/p/6610986.html