Java 为什么getClass().getResource与RandomAccessFile/ReversedLinesFileReader(Apache Commons)存在问题?

Java 为什么getClass().getResource与RandomAccessFile/ReversedLinesFileReader(Apache Commons)存在问题?,java,eclipse,io,Java,Eclipse,Io,我在resources文件夹中有我的txt文件(父文件夹是project文件夹),这个resources文件夹是一个源文件夹(这样Eclipse会自动将其内容复制到/bin root)。在resources文件夹中,我有lottery_archives文件夹和drawArchive_5x36.txt文件。我做了一个“清洁项目”并重新构建了它。我已选中-文件位于/bin/lotking\u archives/drawArchive\u 5x36.txt中 下面的代码有什么问题?为什么FileNot

我在resources文件夹中有我的txt文件(父文件夹是project文件夹),这个resources文件夹是一个源文件夹(这样Eclipse会自动将其内容复制到/bin root)。在resources文件夹中,我有lottery_archives文件夹和drawArchive_5x36.txt文件。我做了一个“清洁项目”并重新构建了它。我已选中-文件位于/bin/lotking\u archives/drawArchive\u 5x36.txt中

下面的代码有什么问题?为什么FileNotFoundException

顺便问一下,为什么所有这些都是使用getClass().getResource,然后是URL->String(我需要给RandomAccessFile构造函数提供字符串文件名),我不完全理解为什么我不能直接给构造函数提供String“/Lotty\u archives/drawArchive\u 5x36.txt”?我觉得有些东西可能不同于jar,而不是本地文件,但不能清楚地表达出来

 import org.apache.commons.io.input.ReversedLinesFileReader;

 public String readLastLine5x36() throws IOException {
    String archiveFileName = "/lottery_archives/drawArchive_5x36.txt";
    URL archiveURL = this.getClass().getResource(archiveFileName);      
    String fileName = archiveURL.toString();        
    File file = new File(fileName);     

    ReversedLinesFileReader reader = new ReversedLinesFileReader(file, Charset.forName("UTF-8"));
    String result = reader.readLine();
archiveURL.toString返回
“文件:/L:/MySeriousProjects/JackPotAlert/JackPotAlert/bin/lotket\u archives/drawArchive\u 5x36.txt”

堆栈跟踪错误:

Exception in thread "main" java.io.FileNotFoundException: \lottery_archives\drawArchive_5x36.txt (Системе не удается найти указанный путь)
at java.io.RandomAccessFile.open0(Native Method)
at java.io.RandomAccessFile.open(RandomAccessFile.java:316)
at java.io.RandomAccessFile.<init>(RandomAccessFile.java:243)
at org.apache.commons.io.input.ReversedLinesFileReader.<init>(ReversedLinesFileReader.java:135)
at org.apache.commons.io.input.ReversedLinesFileReader.<init>(ReversedLinesFileReader.java:78)
at com.codeuniverse.jackpotalert.domain.Archive.readLastLine5x36(Archive.java:128)
at com.codeuniverse.jackpotalert.domain.Archive.main(Archive.java:139)

生成URISyntaxException。

您不能对应用程序jar文件中的文件使用
this.getClass().getResource(archiveFileName)
。因为它不是一个单独的文件

您需要使用
this.getClass().getResourceAsStream(archiveFileName)

查找具有给定名称的资源。搜索资源的规则 与给定类关联的对象由定义类实现 类的加载器。此方法委托给此对象的类 加载器。如果此对象是由引导类装入器装入的,则 方法委托给 ClassLoader.getSystemResourceAsStream(java.lang.String)

在委托之前,将根据 使用此算法的给定资源名称:

如果名称以
'/'
开头(
'\u002f'
),则资源的绝对名称是
'/'
后面的名称部分。 否则,绝对名称的形式如下:

    modified_package_name/name 
其中,修改后的包名是此对象的包名,用
'/'
替换
'.
'\u002e'

参数:

name - name of the desired resource
返回:

 A InputStream object or null if no resource with this name is found 
抛出:

  NullPointerException - If name is null
自:

  JDK1.1
请注意,此方法返回一个
InputStream
,这可能会限制您读取内容的选项

  JDK1.1