Search code examples
javafileurlpackageembedded-resource

Get file to be read from another package


I need to catch a file that is package called files I try use getResourceAsStream or

File file = getClass().getResourceAsStream("files/big.txt")); 

However, is not working. This saying to convert for URL. If in this case I to use URL, I could do a downcasting, but is not working.

What I can do to solve that issue?


Solution

  • add one more slash "/" - If you are accessing from another package
    As Commented Information, To Read the File use openStream() of URL

     URL url = getClass().getResource("/files/big.txt");
         try {
                BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
                String nameList;
                while ((nameList = in.readLine()) != null) {
                    System.out.println(nameList);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }