Frage

My package structure is as follows : src/xxx/ src/yyy/

I have a class in the package src/xxx/ lets call it classA.java and I need to get the path of src/yyy/ how can I do it ? I tried

String s = classA.class.getResourcesAsStream("/yyy/").toString();

but it didn't work.. I need it as a String because I making a new FileReader with that path

War es hilfreich?

Lösung

It's somewhat unclear to me what you're trying to do. But if the file is within a jar file, FileReader isn't going to work anyway - you don't have a file as far as the operating system is concerned. You should just use getResourceAsStream, and then wrap the InputStream in an InputStreamReader. That way you can also specify a character encoding - even when I am using a file, I use FileInputStream and InputStreamReader for that reason.

So you want something like:

try (Reader reader = new InputStreamReader(
         ClassA.class.getResourceAsStream("foo.txt"),
         StandardCharsets.UF_8)) { // Or whichever encoding is appropriate
    // Read from the reader
}

Andere Tipps

Adapt below code to use FileReader

public class Demo 
{
public static void main( String[] args ) {

    ClassLoader cl = Thread.currentThread().getContextClassLoader();

    InputStream is = cl.getResourceAsStream("yyy/FILENAME");
    if (is != null) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        try {
            System.out.println(reader.readLine());
        }
        catch(Exception ex) {
            ex.printStackTrace();
        }
    }

}
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top