Reading txt file from a specific package Java

59,673

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.

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

Share:
59,673
dextervip
Author by

dextervip

Updated on July 12, 2022

Comments

  • dextervip
    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
    Ishimwe Aubain Consolateur about 6 years
    This helped me a lot. tx