當前位置:生活全書館 >

綜合知識

> java讀取檔案路徑怎麼寫

java讀取檔案路徑怎麼寫

1. java web中讀取檔案,相對路徑怎麼寫

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

java讀取檔案路徑怎麼寫

舉例:

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

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

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

2. 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

3. java讀取檔案路徑

你的頭是e://tttt11.PNG不是e://tttt11//1.PNG???如果頭是e://tttt11//1.PNG,filepath沒有用,去掉。

這段這麼改:for (i=0; i <= str.length(); i += 2) { if (i == str.length() - 1 || i == str.length() - 2) break; else fileName = str.substring(i); } // System.out.println(filePath); if(ii!=100) fileName = str.substring(i);。

..後面不改.如果頭是e://tttt11.PNG,那這個和下面的迴圈規律不一樣,大概寫下:if(ii==1)filePath=".PNG";把我上面修改後的程式碼加到else裡就行了(用我上面修改後的程式碼,不然你的尾還是顯不出來)。

4. java 如何獲取檔案路徑

public void doGet(HttpServletRequest request ,HttpServletResponse response )

throws ServletException ,IOException{

OutputStream out;//輸出響應正文的輸出流

InputStream in; //讀取本地檔案的輸入流

//獲取filename 請求引數

String filename =requeset.getParameter("filename");

if(filename==null){

out=response.getOutputStream();

out.write("please input filename.".getBytes());

out.close;

return;

}

//獲得讀取本地檔案的輸入流

in=getServletContext().getResourceAsStream("/store"+filename);

int length=in.available();

}

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等方式讀取

標籤: java 檔案 路徑 讀取
  • 文章版權屬於文章作者所有,轉載請註明 https://shqsg.com/zonghezhishi/3ymelv.html