【问题标题】:Reading txt file from a specific package Java从特定包 Java 中读取 txt 文件
【发布时间】:2011-05-20 16:00:32
【问题描述】:
我正在尝试读取特定包中的文本文件,但它返回找不到。我可以插入绝对路径来读取它,但我想在不插入绝对路径的情况下读取它。
String texto = "Utils/CEP/Cidades/" + estado + ".txt";
FileReader fr = new FileReader(texto);
BufferedReader in = new BufferedReader(fr);
我该怎么办?
谢谢
【问题讨论】:
标签:
java
file
text
package
【解决方案1】:
你可以使用
InputStream in =
getClass().getResourceAsStream("/Utils/CEP/Ciades/" + estado + ".txt");
Reader fr = new InputStreamReader(in, "utf-8");
一些旁注:不要在包名中使用大写字母;使用变量的英文名称。这些是公认的做法和惯例。
【解决方案3】:
为了整体的可移植性,考虑使用 File.separator 代替正斜杠,但是 getResourceAsStream 应该可以工作。请记住,如果您在 Eclipse 中工作,那么您的类文件可能会在相对于您的工作目录的 bin 中,所以如果它只是在您的项目文件夹中,那么您拥有它的方式应该可以工作,而不是 getResourceAsStream。或者,如果您要访问的资源位于源文件夹中,则每当您清理项目时,它将被复制到 bin 中,因此 getResourceAsStream 将起作用。
【解决方案4】:
现在可能有点晚了,这可以帮助许多其他人。这些是访问项目中可用资源的方法
从默认包中获取资源
// 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()
希望这会有所帮助。干杯!!