5

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

              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)
4

3 回答 3

7

如果您想从 jar 文件(即从类路径)中加载文件,请参阅此答案以获取有关如何获取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");

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

于 2013-07-25T18:58:26.307 回答
1

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

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

假设命名的资源与 .lol.txt表示和返回的类在同一个包中getClass()

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

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");

在此处阅读 javadoc。

于 2013-07-25T18:20:52.960 回答
0

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

在此处输入图像描述

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

在此处输入图像描述

在此处输入图像描述

于 2021-06-01T08:12:42.713 回答