開心生活站

位置:首頁 > 綜合知識 > 

java讀取文件的路徑怎麼寫

1. 如何查看java讀取文件的路徑

File類有兩個常用方法可以得到文件路徑一個是:getCanonicalPath(),另一個是:getAbsolutePath(),可以通過File類的實例調用這兩個方法例如file.getAbsolutePath()其中file是File的實例對象。

java讀取文件的路徑怎麼寫

下面是一個具體例子:123456789101112131415public class PathTest{public static void main(String[] args){File file = new File(".srcbaidu");System.out.println(file.getAbsolutePath());try{System.out.println(file.getCanonicalPath());} catch (IOException e){e.printStackTrace();}}}getAbsolutePath()和getCanonicalPath()的不同之處在於,getCanonicalPath()得到的是一個規範的路徑,而getAbsolutePath()是用構造File對象的路徑+當前工作目錄。例如在上面的例子中.(點號)代表當前目錄。

getCanonicalPath()就會把它解析爲當前目錄但是getAbsolutePath()會把它解析成爲目錄名字(目錄名字是點號)。下面是上面程序在我電腦上的輸出:G:xhuojkonw.srcbaiduG:xhuojkonwsrcbaidu。

2. java web中讀取文件,相對路徑怎麼寫

相對路徑的話,可以先獲取到當前文件的編譯路徑,之後在找到想找文件的路徑的思路來實現。

舉例:

XMLS.class.getClass().getResourceAsStream("/test/test.txt");

解釋:XMLS.class.getClass()是獲取當前的類編譯路徑,之後通過getResourceAsStream的形式即可找到要讀取的文件的路徑。

備註:這個方法中後面的路徑也可以通過截取的形式來進行路徑獲取,實現原理都是找到當前類路徑,之後通過相對位置找到另外文件路徑。

3. java獲取某個文件夾的路徑怎麼寫

File類有兩個常用方法可以得到文件路徑一個是:getCanonicalPath(),另一個是:getAbsolutePath(),可以通過File類的實例調用這兩個方法例如file.getAbsolutePath()其中file是File的實例對象。下面是一個具體例子:

public class PathTest

{

public static void main(String[] args)

{

File file = new File(".srcbaidu");

System.out.println(file.getAbsolutePath());

try

{

System.out.println(file.getCanonicalPath());

} catch (IOException e)

{

e.printStackTrace();

}

}

}

getAbsolutePath()和getCanonicalPath()的不同之處在於,getCanonicalPath()得到的是一個規範的路徑,而getAbsolutePath()是用構造File對象的路徑+當前工作目錄。例如在上面的例子中.(點號)代表當前目錄。getCanonicalPath()就會把它解析爲當前目錄但是getAbsolutePath()會把它解析成爲目錄名字(目錄名字是點號)。

下面是上面程序在我電腦上的輸出:

G:xhuojkonw.srcbaidu

G:xhuojkonwsrcbaidu

4. java文件讀寫的文件應該放哪個路徑

1。

如果你用的eclipse,那麼project>>properties>>打開屬性設置窗口有一項java build path,點開最下面有個default output folder,那裏有路徑,比如:axis2如果你要讀的文件名字爲1.txt的話你就把它放到C:eclipseworkspacesaxis2下面就行了。2。

如果你直接用cmd javac編譯的那麼假設你的java文件放在*axis2Exam9FileInputStream.java編譯好的class文件也在同一個目錄執行程序要在*axis2目錄java Exam9.FileInputDemo而你的文件要放在*axis2Exam9 3。也可以用絕對路徑。

5. java怎麼通過文件的路徑讀取文件

package file.system.demo.exception;

import java.io.File;

import java.io.FileNotFoundException;

import java.util.Scanner;

public class ReadFile {

public static String getFile(String realpath) {

Scanner scanner = null;

String text = "";

try {

File file= new File(realpath);

scanner = new Scanner(file);

} catch (FileNotFoundException e) {

e.printStackTrace();

}

if(scanner!=null){

while(scanner.hasNextLine()){

text+=scanner.nextLine();

}

scanner.close();

}

//System.out.println(text);

return text;

}

static class InnerTest{

public static void main(String[] args) {

String realpath = "D:test.txt";

String text=getFile(realpath);

System.out.println(text);

}

}

}

實現方式有很多,還可以用字節流FileInputStream,字符流FileReader等方式讀取