如何将类路径中的文本文件加载到Java中的String []

时间:2017-03-08 14:10:51

标签: java string file

我试图将文本文件中的内容读取到String。在Netbeans IDE中,everthing工作得很好,但如果我编译没什么用。

这是我的代码:

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;
}

这是我得到的例外:

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)

我不知道自己做错了什么!

2 个答案:

答案 0 :(得分:3)

使用 getClass().getResourceAsStream(Name)

而不是

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

最后你会得到:

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

将资源作为文件访问总是一个坏主意,因为资源可以在JAR文件中,因此不能作为公共文件直接访问。但是,如果您以流的形式访问它,则可以随时访问它。

答案 1 :(得分:1)

如果生成jar文件,则必须将txt文件放在jar文件夹所在的文件夹中。