将文件从src文件夹加载到阅读器中

时间:2013-07-25 17:59:53

标签: java file load directory src

我想知道如何从lol.txt文件夹中将文件src加载到我的close方法中。到目前为止的代码:

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

启动时出现控制台错误:

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)

3 个答案:

答案 0 :(得分:7)

如果您想从jar文件(即类路径)中加载文件,请参阅this answer以获取有关如何获取InputStream的更多选项。在下面的代码中,我遗漏了异常处理并删除了您的Random相关代码。

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

编辑:您的文件夹结构似乎有问题,或者您使用了错误的包/文件名。只是为了清楚。目前,您似乎在main包下有一个名为main的类。您的文件夹结构应该是这样的:

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

编译时,你的lol.txt文件(btw是小写 L's 而不是数字 1 对吗?)应该复制到/bin/main/文件夹< / p>

如果是这种情况,那么使用如下代码: InputStream in = getClass().getClassLoader().getResourceAsStream("main/lol.txt");

如果您的文件夹结构不同,请相应更改

答案 1 :(得分:1)

如果要从类路径获取文件(资源)的InputStream,可以执行以下操作

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

假设名为lol.txt的资源与getClass()所表示和返回的类位于同一个包中。

如果资源不在同一个包中,您可以在路径前加上/,告诉方法查看类路径的根。

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

如果您尝试使用static方法访问资源,则无法访问this。你需要使用

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

Read the javadoc here.

答案 2 :(得分:0)

您可以打开多种类型的文件。它们可以是 csv、json、xml、序列化等。它们可以位于 jar 文件、压缩文件(如 zip)中、被加密、位于 Internet 中的 URL 中等。对文件的访问可能需要访问代码(ssh 等)。我假设 lol.txt 文件是一个简单的文本文件,可以被任何文本编辑器(例如记事本)打开,并且位于当前项目的 src 文件夹中。下面,你可以找到一个方法,找到文件的动态位置并打印内容。仅供参考,Reader 的其他子类是: 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