簡體   English   中英

從特定包Java中讀取txt文件

[英]Reading txt file from a specific package Java

我正在嘗試讀取特定包中的文本文件,但它返回無法找到。我可以讀取它插入絕對路徑但我想讀取它而不插入絕對路徑。

String texto = "Utils/CEP/Cidades/" + estado + ".txt";
FileReader fr = new FileReader(texto);
BufferedReader in = new BufferedReader(fr);

我應該怎么做?

謝謝

您可以使用

InputStream in = 
   getClass().getResourceAsStream("/Utils/CEP/Ciades/" + estado + ".txt");
Reader fr = new InputStreamReader(in, "utf-8");

一些旁注:不要在包名中使用大寫字母; 使用變量的英文名稱。 這些是公認的做法和慣例。

可能還有點晚,這可以幫助其他許多人。 這些是訪問項目中可用資源的方法

從默認包中獲取資源

// Getting Resource as file object
File f = new File(getClass().getResource("/excludedir.properties").getFile());

// Getting resource as stream object
InputStream in = getClass().getResourceAsStream("/excludedir.properties");

從特定包中獲取資源

// Getting Resource as file object
File f = new File(getClass().getResource("/com/vivek/core/excludedir.properties").getFile());

// Getting resource as stream object
InputStream in = getClass().getResourceAsStream("/com/vivek/core/excludedir.properties");

注意: getclass()是一個非靜態函數,不能從靜態上下文中調用。 如果要從靜態上下文中調用使用

YourClassName.class.getResource("/com/vivek/core/excludedir.properties").getFile()

希望這可以幫助。 干杯!!

如果文本文件與類文件存在於同一結構中,那么您可能更適合使用getResourceAsStream。

http://download.oracle.com/javase/6/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String)

為了實現可移植性,請考慮使用File.separator代替正斜杠,但是getResourceAsStream應該可以使用。 請記住,如果你在eclipse中工作,你的類文件可能會在你的工作目錄中的bin中,所以如果它只在你的項目文件夾中,你應該使用它的方式,但不是getResourceAsStream。 或者,如果要訪問的資源位於源文件夾中,則只要清理項目,它就會被復制到bin中,因此getResourceAsStream將起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM