Quantcast
Channel: Where to put resources and access it in Java Project (in IntelliJ)? How to read from it then? - Stack Overflow
Viewing all articles
Browse latest Browse all 2

Answer by Stefano Riffaldi for Where to put resources and access it in Java Project (in IntelliJ)? How to read from it then?

$
0
0

ok, as I suspected, the space (%20) in the folder name seems to not be nice with URL, so I've recreated that behavior and got a FileNotFoundException (using Java 1.8)

Using ClassLoader.getSystemResourceAsStream all works fine, here's:

public static void main(String[] args) throws IOException {    InputStream inputStream = ClassLoader.getSystemResourceAsStream("resources/coding_qual_input.txt");    if (inputStream != null) {        BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));        for (String line = in.readLine(); line != null; line = in.readLine()) {            System.out.println(line);        }        in.close();        inputStream.close();    }}

or (but I really discourage it) use String.replace to substitute "%20" with " " and still use URL

public static void main(String[] args) throws IOException {    URL fileURL = Main.class.getResource("resources/coding_qual_input.txt");    System.out.println(fileURL);    if (fileURL != null) {        File file = new File(fileURL.getFile().replace("%20", " "));        BufferedReader in = new BufferedReader(new FileReader(file));        for (String line = in.readLine(); line != null; line = in.readLine()) {            System.out.println(line);        }        in.close();    }}

or (again, not the best way imho) use URL.openStream to directly open an InputStream without use File

InputStream inputStream = fileURL.openStream();BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));for (String line = in.readLine(); line != null; line = in.readLine()) {    System.out.println(line);}

Viewing all articles
Browse latest Browse all 2

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>