从.jar文件读取文本文件 [英] Reading a Text File From a .jar File

查看:117
本文介绍了从.jar文件读取文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个菜鸟问题。

我目前正在编写一个程序,该文件使用File和Scanner类从文本文件中提取大量数据,如下所示:

I'm currently writing a program that takes in alot of data from a text file using the File and Scanner class as shown below:

   File data = new File("champdata.txt");
   Scanner read = new Scanner(data);
   read.useDelimiter("%");

然后在IDE中,但当我运行程序时,扫描程序会正确地从文本文件中检索数据作为.jar文件,无法检索该文件。

The Scanner then retrieves data from the text file correctly while in the IDE, but when I run the program as a .jar file, the file cannot be retrieved.

我已经阅读了一些有关将文本文件添加到.jar文件本身,以及使用InputStream和BufferedReader类可以读取文件,但我从未使用过这些类,也不了解它们的不同之处/如何使用它们代替File和Scanner类。

I've read a little about adding a text file to the .jar file itself, and using the InputStream and BufferedReader classes to read the file, but I have never used these classes, nor do I understand what they do differently/how to use them in place of the File and Scanner classes.

有人可以帮我吗?

推荐答案

Scanner 类具有构造函数 Scanner(InputStream) ;因此,您仍然可以像以前一样使用此类读取数据。

The Scanner class has a constructor Scanner(InputStream); so you can still use this class to read the data like you did before.

所有您需要做的就是从Jar中读取文件,您可以像这样因此:

All you have to do is to read the file from the Jar, you can do this like so:

InputStream is = getClass().getResourceAsStream("champdata.txt");
Scanner read = new Scanner(is);
read.useDelimiter("%");

名为 champdata.txt 的文件在哪里位于jar文件(仅是zip文件)的根目录下,您可以使用任何解压缩程序来验证文件的位置。

Where the file named champdata.txt is located at the root of your jar file (which is just a zip file, you can use any unzipper to verify where the file is being located).

现在,如果需要为了在IDE中进行开发时具有相同的功能,请将文件放置在源目录中,以便在构建项目时将其放置在 classes 文件夹中。这样,可以使用 getResourceAsStream()

Now if you want to have the same functionality while developing in your IDE, place the file in your source directory, so that when the project is being built, it is placed in your classes folder. This way, the file can be loaded as described above using getResourceAsStream()

这篇关于从.jar文件读取文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆