Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load a file from src folder into a reader

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)
like image 405
Vitalij Kornijenko Avatar asked Jul 25 '13 17:07

Vitalij Kornijenko


People also ask

What is a src folder for?

The src stands for source. The /src folder comprises of the raw non-minified code. The /src folder is used to store the file with the primary purpose of reading (and/or editing) the code. The /src folder contains all the sources, i.e. the code which is required to be manipulated before it can be used.

How do you load properties file from resources folder in Java?

In Java, we can use getResourceAsStream or getResource to read a file or multiple files from a resources folder or root of the classpath. The getResourceAsStream method returns an InputStream . // the stream holding the file content InputStream is = getClass().


2 Answers

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

like image 79
c.s. Avatar answered Nov 14 '22 23:11

c.s.


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.

like image 21
Sotirios Delimanolis Avatar answered Nov 14 '22 22:11

Sotirios Delimanolis