开发者

Reading txt file from a specific package Java

I'm trying to read a text file in a specific package but it return that couldn't be found.I can read it inserting the absolute path but i want to read it wit开发者_如何学编程hout inserting the absolute path.

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

How should i do?

Thanks


You can use

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

A few sidenotes: don't use capital letters in package names; use English names of your variables. These are accepted practices and conventions.


It could be little late still this could help many other. These are ways to access the resources available in the project

Getting resources form the default package

// 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 resources from specific packages

// 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");

Note : getclass() is a non-static function which cannot be called form the static context. If you want to call from the static context use

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

Hope this helps. Cheers!!


If the text file exists within the same structure as your class files, then you may be better suited using getResourceAsStream.

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


For total portability, consider using File.separator in place of forward slashes, but yeah getResourceAsStream should work. Keep in mind, that if you're working in eclipse, your class files will probably be in bin with respect to your working directory so if it's just in your project folder, the way you have it should work, but not getResourceAsStream. Alternatively, if the resource you want to access is in a source folder, it will be copied into bin whenever you clean your project so getResourceAsStream will work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜