java - 将 src 文件夹中的文件加载到阅读器中

标签 java file load directory src

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

              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)

最佳答案

如果您想从 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 文件(顺便说一句,那些是小写的 L 而不是数字 1 对吧?)应该被复制到 /bin/main 下/文件夹

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

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

关于java - 将 src 文件夹中的文件加载到阅读器中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17865427/

相关文章:

java - 为什么 Java 提供了两种从队列中移除元素的方法?

java - 在我的应用程序中捕获谷歌聊天发送的传出数据包

c - 在具有固定宽度列的文本文件上使用 fscanf

c# - .NET 可以加载和解析等效于 Java Properties 类的属性文件吗?

WPF负载控制问题

java - android 列表在第一次运行时在 recyclerview 中获得 0 值

java - 使用列表迭代器访问对象的方法

load - 在 Common Lisp 中加载文件时读取下一行

java - 如何使用缓冲写入器在文件中逐行写入?

objective-c - 在 iOS 中读取文件时出现 malloc 错误