Load a file from src folder into a reader
Asked Answered
F

3

5

I would like to know how can I load a file lol.txt from src folder into my close method. The code so far:

              public void close() throws IOException {
        boolean loadFromClasspath = true;
        String fileName = "..."; // provide an absolute path here to be sure that file is found
        BufferedReader reader = null;
        try {

            if (loadFromClasspath) {
                // loading from classpath
                // see the link above for more options
                InputStream in = getClass().getClassLoader().getResourceAsStream("lol.txt"); 
                reader = new BufferedReader(new InputStreamReader(in));
            } else {
                // load from file system
                reader = new BufferedReader(new FileReader(new File(fileName)));
            }

            String line = null;
            while ( (line = reader.readLine()) != null) {
                // do something with the line here
                System.out.println("Line read: " + line);
            }
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null,e.getMessage()+" for lol.txt","File Error",JOptionPane.ERROR_MESSAGE);
        } finally {
            if (reader != null) {
                reader.close();  
            }
        }
    }

Console error output on initiation:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at java.io.Reader.<init>(Unknown Source)
at java.io.InputStreamReader.<init>(Unknown Source)
at main.main.close(main.java:191)
at main.main$1.windowClosing(main.java:24)
at java.awt.Window.processWindowEvent(Unknown Source)
at javax.swing.JFrame.processWindowEvent(Unknown Source)
at java.awt.Window.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$000(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Fruitless answered 25/7, 2013 at 17:59 Comment(5)
If you just want to read a file, that looks good. If you want to use those files as Java classes or something, there's probably more to it.Spode
What does lot.txt contains ? Plain text or a class definition ?Kelliekellina
Class#getResourceAsStream(String)Ampere
@MaximePiraux Contains lines of strings in format "Hello guyz..."Fruitless
The question does not talk about any jar file nor a specific location or file in a jar file. The question you ask is about how to read the content of a file into a Reader so I don't see how you decided the correct answer. And the path should not be absolute if you want your code to work in other computers, am I wrong?Yoho
P
7

If you like to load the file from inside a jar file (i.e. from classpath) please see this answer for more options on how to get an InputStream. In the code below I have left-out exception handling and removed your Random related code.

public void close() {
    boolean loadFromClasspath = true;
    String fileName = "..."; // provide an absolute path here to be sure that file is found
    BufferedReader reader = null;
    try {
        
        if (loadFromClasspath) {
            // loading from classpath
            // see the link above for more options
            InputStream in = getClass().getClassLoader().getResourceAsStream("absolute/path/to/file/inside/jar/lol.txt"); 
            reader = new BufferedReader(new InputStreamReader(in));
        } else {
            // load from file system
            reader = new BufferedReader(new FileReader(new File(fileName)));
        }

        String line = null;
        while ( (line = reader.readLine()) != null) {
            // do something with the line here
            System.out.println("Line read: " + line);
        }
    } catch (IOException e) {
        JOptionPane.showMessageDialog(null,e.getMessage()+" for lol.txt","File Error",JOptionPane.ERROR_MESSAGE);
    } finally {
        if (reader != null) {
            reader.close();  
        }
    }
}

Edit: It seems that you are either doing something wrong with your folder structure or you are using a wrong package/file name. Just to be clear. At the moment you seem to have a class called main under a main package. Your folder structure should be something like this:

+ src/
   + main/
      main.java
      lol.txt

When you compile, your lol.txt file (btw those are lowercase L's not the digit 1 right?) should be copied under /bin/main/ folder

If this is the case then use the code like this: InputStream in = getClass().getClassLoader().getResourceAsStream("main/lol.txt");

If your folder structure is different please change accordingly

Paronychia answered 25/7, 2013 at 18:58 Comment(9)
@VitalijKornijenko This code is tested and works. Are you trying the classpath case? What value do you use as an argument to getResourceAsStream()? And what package is your file in?Paronychia
If the classpath case means accessing files within jar where the mains classes are located then yes. Using ur exact same code only throws IOException. Created a new package recently maainFruitless
@VitalijKornijenko are you using my code or some other's code? I don't write getClass().getResourceAsStream("lol.txt");. I am using getClass().*getClassLoader()*.getResourceAsStream("lol.txt"); If you use the class approach please add an extra "/" i.e. use "/lol.txt". Please see the link in my answer. It will become clear to youParonychia
@VitalijKornijenko if you now use a package "main" then you will try to loas as getClassLoader().getResourceAsStream("main/lol.txt"); and the text file should be under src/main folderParonychia
Using ur code and about the getCalse().getResourceAsStream() line, I tried: InputStream in = getClass().getClassLoader().getResourceAsStream("lol.txt"); InputStream in = getClass().getClassLoader().getResourceAsStream("/lol.txt");Fruitless
@VitalijKornijenko see my previous comment. With classloader you never add a "/". If you use my code and you have loadFromClasspath = true; as I have it in my answer then: a) if you have your file in default package call it as getClass().getClassLoader().getResourceAsStream("lol.txt");. If your file is under main package call it as getClass().getClassLoader().getResourceAsStream("main/lol.txt"); It does not matter where your Main class is using this approach. If you still get an error look where your files are compiled (under bin in eclipse) to check if the file has been copied thereParonychia
Got something new: Exception in thread "main" java.lang.NullPointerException at java.io.Reader.<init>(Unknown Source) at java.io.InputStreamReader.<init>(Unknown Source) at main.main.close(main.java:197) at main.main.<init>(main.java:20) at main.Driver.main(Driver.java:5)Fruitless
Ok I figured what the problem was. The file is read inside the bin folder not src folder so that makes stuff clear for me and I mixed stuff up, sorry >.<. I'll respond once I get all working.Fruitless
Ok thanks a lot for you effort :D marking you answer as THE answer. CheersFruitless
A
1

If you want to get the InputStream of a file (resource) from the classpath, you can do the following

InputStream in = this.getClass().getResourceAsStream("lol.txt");

assuming the resource named lol.txt is in the same package as the class represented and returned by getClass().

If the resource is not in the same package, you can prefix the path with a / to tell the method to look at the root of the classpath.

InputStream in = this.getClass().getResourceAsStream("/lol.txt"); // or /some/resource/path/lol.txt for some other path starting at root of classpath

If you're trying to access the resource from a static method, you won't have access to this. You'll need to use

YourClass.class.getResourceAsStream("/lol.txt");

Read the javadoc here.

Ampere answered 25/7, 2013 at 18:20 Comment(12)
Could you please take a look at the code. It gives out me some errors :/Fruitless
@VitalijKornijenko Please also show the error text/stacktrace.Ampere
@VitalijKornijenko You can't use a FileReader with an InputStream. Use an InputStreamReader. new InputStreamReader(in);. Also, careful when reading lines. Always check if there IS a line first.Ampere
the file will always have a line (100 + lines) and the file is untochable. Also updated the code and error report on initiation.Fruitless
@VitalijKornijenko Still, be careful. As for the exception, your call to getResourceAsStream returns null. Is the file in the same package the class you're calling the method from? Look at my answer, if it's not, you should prefix the path with /.Ampere
All the classes and all the files are in the same package '(default package)'Fruitless
@VitalijKornijenko If you try with the /, does it work? If not, could you post the structure of your jar. We might be missing something.Ampere
Didn't work with the / and so far I've been running everything within eclipse not executing the jar file. But I have exported jar file and saw that there is no lol.txt in jar.Fruitless
@VitalijKornijenko That means the lol.txt file was not on the classpath in either scenario.Ampere
@VitalijKornijenko Then the problem might have to do with the fact that there is no package. Create one and put your 3 files in it.Ampere
same thing. Created a new package 'main' and tried with and without /. Same error and everything.Fruitless
In case I've missed something I pasted the current code I have and the current errors JUST IN CASE.Fruitless
Y
0

There are many types of files that you can open. They can be csv, json, xml, serialized, etc. They can be located in a jar file, in a compressed file such as zip, be encrypted, be located in a URL in the internet, etc. The access to file might need access code (ssh ,etc). I assume that the lol.txt file is a simple text file that can be opened by any text editor such as Notepad and is located in the src folder of the current project. In the following, you can find a method that finds the dynamic location of the file and print the content. FYI, Other sub-classes of Reader are: enter image description here

enter image description here

public void loadFileFromSrcToReader(String fileNameToOpen) {
    // a text file is located in src folder in the project
    Path rootDir = Paths.get(".").normalize().toAbsolutePath();
    File file = new File(rootDir.toString() + "/src/"+fileNameToOpen);
    Reader input = null;
    if (file.exists()) {
        try {
            input = new FileReader(file);
            // Checks if reader is ready
            BufferedReader br = new BufferedReader(input);
            String line = "";
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
            // Closes the reader
            input.close();
        }  catch (IOException e) {
            e.printStackTrace();
        }
    }
}

enter image description here

enter image description here

Yoho answered 1/6, 2021 at 8:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.