java讀取檔案的路徑怎麼寫
- 綜合知識
- 關注:1.73W次
File類有兩個常用方法可以得到檔案路徑一個是:getCanonicalPath(),另一個是:getAbsolutePath(),可以通過File類的例項呼叫這兩個方法例如file.getAbsolutePath()其中file是File的例項物件。
下面是一個具體例子: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等方式讀取
- 文章版權屬於文章作者所有,轉載請註明 https://shqsg.com/zonghezhishi/xz6pkl.html