1

Im trying to read the content from a text file to a String. In the Netbeans IDE everthing works perfectly, but if I compile nothing works.

Here's my code:

private String[] getSplashes(String Name) {
    String[] sp = null;
    try {
        String content = new Scanner(new File(getClass().getResource(Name).getFile())).useDelimiter("\\Z").next();
        sp = content.split(";");
    } catch (IOException ex) {
    }
    return sp;
}

Here's the exception I get:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at jumpover.MenuDrawing.getRandomSplash(MenuDrawing.java:51)
    at jumpover.MenuDrawing.<init>(MenuDrawing.java:47)
    at jumpover.JOFrame.<init>(JOFrame.java:18)
    at jumpover.JOFrame.lambda$main$0(JOFrame.java:46)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$500(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$JavaSecurityAccessImpl.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)

I don't know what I am doing wrong!

2
  • In the Netbeans IDE everthing works perfectly, but if I compile nothing works. you mean when you try to compile externally using javac command ? Commented Mar 8, 2017 at 14:13
  • Possible duplicate of What is simplest way to read a file into String? Commented Mar 8, 2017 at 14:13

2 Answers 2

4

Use getClass().getResourceAsStream(Name)

instead of

new File(getClass().getResource(Name).getFile())

In the end you get:

String content = new Scanner(getClass().getResourceAsStream(Name)).useDelimiter("\\Z").next();

Accessing a resource as a file is always a bad idea as the resource can be inside of a JAR file and therefore not directly accessible as common file. However if you access it as stream you can always access it.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you Robert! Works perfectly! :)
1

if you generate a jar file you have to put the txt file in the same folder as jar's folder.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.