Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ssh/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 将文件从src文件夹加载到读卡器中_Java_File_Load_Directory_Src - Fatal编程技术网

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

Java 将文件从src文件夹加载到读卡器中,java,file,load,directory,src,Java,File,Load,Directory,Src,我想知道如何从src文件夹将文件lol.txt加载到我的close方法中。迄今为止的守则: public void close() throws IOException { boolean loadFromClasspath = true; String fileName = "..."; // provide an absolute path here to be sure that file is found Buf

我想知道如何从
src
文件夹将文件
lol.txt
加载到我的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)
线程“AWT-EventQueue-0”java.lang.NullPointerException中的异常 位于java.io.Reader。(未知源) 位于java.io.InputStreamReader。(未知源) 在main.main.close(main.java:191) main.main$1.windowClosing(main.java:24) 位于java.awt.Window.processWindowEvent(未知源) 位于javax.swing.JFrame.processWindowEvent(未知源) 位于java.awt.Window.processEvent(未知源) 位于java.awt.Component.dispatchEventImpl(未知源) 位于java.awt.Container.dispatchEventImpl(未知源) 位于java.awt.Window.dispatchEventImpl(未知源) 位于java.awt.Component.dispatchEvent(未知源) 位于java.awt.EventQueue.dispatchEventImpl(未知源) 位于java.awt.EventQueue.access$000(未知源) 在java.awt.EventQueue$3.run处(未知源) 在java.awt.EventQueue$3.run处(未知源) 位于java.security.AccessController.doPrivileged(本机方法) 位于java.security.ProtectionDomain$1.doIntersectionPrivilege(未知源) 位于java.security.ProtectionDomain$1.doIntersectionPrivilege(未知源) 在java.awt.EventQueue$4.run处(未知源) 在java.awt.EventQueue$4.run处(未知源) 位于java.security.AccessController.doPrivileged(本机方法) 位于java.security.ProtectionDomain$1.doIntersectionPrivilege(未知源) 位于java.awt.EventQueue.dispatchEvent(未知源) 位于java.awt.EventDispatchThread.pumpOneEventForFilters(未知源) 位于java.awt.EventDispatchThread.pumpEventsForFilter(未知源) 位于java.awt.EventDispatchThread.pumpEventsForHierarchy(未知源) 位于java.awt.EventDispatchThread.pumpEvents(未知源) 位于java.awt.EventDispatchThread.pumpEvents(未知源) 位于java.awt.EventDispatchThread.run(未知源)
如果要从类路径获取文件(资源)的
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
如果您试图从
静态
方法访问资源,您将无法访问
。你需要使用

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

如果您想从jar文件内部(即从类路径)加载文件,请参阅以获取有关如何获取
输入流的更多选项。在下面的代码中,我省略了异常处理,删除了您的
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
的类。您的文件夹结构应如下所示:

编译时,应该将lol.txt文件(顺便说一句,这些文件是小写的L而不是数字1对吗?)复制到
/bin/main/
文件夹下

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


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

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


如果您只想读取一个文件,这看起来不错。如果您想将这些文件用作Java类或其他东西,可能还有更多内容?纯文本还是类定义?
class#getResourceAsStream(String)
@MaximePriraux包含格式为“Hello guyz…”的字符串行。问题不涉及任何jar文件,也不涉及jar文件中的特定位置或文件。你问的问题是如何将文件内容读入阅读器,因此我不知道你是如何决定正确答案的。如果你想让你的代码在其他计算机上运行,路径不应该是绝对的,我错了吗?请你看一下代码。它告诉我一些错误:/@VitalijKornijenko请同时显示错误文本/stacktrace。@VitalijKornijenko您不能将
文件读取器
输入流
一起使用。使用
InputStreamReader
<代码>新的InputStreamReader(in)。另外,读台词时要小心。始终先检查是否有一行。文件将始终有一行(100多行),并且文件是不可访问的。还更新了启动时的代码和错误报告。@VitalijKornijenko仍然要小心。对于异常,对
getResourceAsStream
的调用返回
null
。在同一个包中的文件就是从中调用方法的类吗?看看我的答案,如果不是,你应该在路径前面加上
/
@VitalijKornijenko前缀。这段代码已经过测试并且有效。您正在尝试classpath案例吗?您使用什么值作为
getResourceAsStream()
的参数?您的文件在哪个包中?如果classpath的情况意味着访问jar中主要类所在的文件,那么是的。使用完全相同的代码只会引发IOException。最近创建了一个新包maain@VitalijKornijenko你是用我的代码还是别人的代码?我不写
getClass().getResourceAsS
+ src/
   + main/
      main.java
      lol.txt
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();
        }
    }
}