Reading txt file from a specific package Java
Solution 1
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.
Solution 2
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!!
Solution 3
If the text file exists within the same structure as your class files, then you may be better suited using getResourceAsStream.
dextervip
Updated on July 12, 2022Comments
-
dextervip almost 2 years
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 without 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
-
Ishimwe Aubain Consolateur about 6 yearsThis helped me a lot. tx