4

I have a rookie question.

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

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.

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.

Can anyone help me out?

4

2 に答える 2

3

埋め込みリソースであるため、URL でファイルを取得する必要があります。詳細については、埋め込みリソース Wikiを参照してください。

アップデート

したがって、テキスト ファイルを src フォルダーの「Resource」フォルダーに配置した場合、使用する URL は「resources/champdata.txt」になります。

いいえResource。Jar 内のパスにある場合、文字列は次のようにする必要があります。

..getResource("/Resource/champdata.txt");

resourcesパスにある場合:

..getResource("/resources/champdata.txt");

文字列は正確な文字 (複数&) である必要があります。

于 2012-10-18T18:15:49.177 に答える
2

ScannerクラスにはコンストラクターがありScanner(InputStream)ます。そのため、以前と同じように、このクラスを使用してデータを読み取ることができます。

Jar からファイルを読み取るだけで、次のように実行できます。

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

指定されたファイルchampdata.txtが jar ファイルのルートにある場所 (これは単なる zip ファイルです。ファイルの場所を確認するには、任意の解凍ツールを使用できます)。

IDE での開発中に同じ機能を使用したい場合は、ファイルをソース ディレクトリに配置して、プロジェクトのビルド時にclassesフォルダーに配置されるようにします。このようにして、ファイルは上記のようにロードできます。getResourceAsStream()

于 2012-10-18T18:42:49.010 に答える