【发布时间】:2018-09-28 20:32:45
【问题描述】:
我在资源文件夹中有我的 txt 文件(父文件夹是项目文件夹),这个资源文件夹是一个源文件夹(这样 Eclipse 会自动将其内容复制到 /bin 根目录)。在资源文件夹中,我有 lottery_archives 文件夹,其中包含 drawArchive_5x36.txt 文件。我做了“清洁项目”并再次构建它。我检查了 - 文件存在于 /bin/lottery_archives/drawArchive_5x36.txt
下面的代码有什么问题?为什么 FileNotFoundException?
顺便说一句,为什么所有这些都与 getClass().getResource 然后 URL->String 共舞(我需要将 String fileName 给 RandomAccessFile 构造函数),我不完全理解为什么我不能给 String "/lottery_archives /drawArchive_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 返回"file:/L:/MySeriousProjects/JackPotAlert/JackPotAlert/bin/lottery_archives/drawArchive_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)
尝试将 URL 转换为 URI 并将 URI 提供给 RandomAccessFile 构造函数(通过 apache 类)
String archiveFileName = "/lottery_archives/drawArchive_5x36.txt";
URL archiveURL = this.getClass().getResource(archiveFileName);
File file = new File(archiveURL.toURI());
产生 URISyntaxException。
【问题讨论】: