6

重複の可能性:
ファイルとしての Java リソース

私はJavaが初めてで、Jarファイル内のテキストファイルを取得しようとしています.

jar ファイルを実行する時点で、jar ファイルと同じフォルダーにテキスト ファイルを配置する必要があります。テキストファイルがそこにない場合、私はNullPointerException避けたい.

私がやりたいのは、jar内のtxtファイルを取得することなので、この問題は発生しません。いくつかのガイドを試しましたが、うまくいかないようでした。私の現在の読み取り機能は次のようになります。

public static HashSet<String> readDictionary()
{
    HashSet<String> toRet = new HashSet<>();
     try
     {
            // Open the file that is the first 
            // command line parameter
            FileInputStream fstream = new FileInputStream("Dictionary.txt");
        try (DataInputStream in = new DataInputStream(fstream)) {
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;
            //Read File Line By Line
            while ((strLine = br.readLine()) != null)   {
            // Read Lines
                toRet.add(strLine);
            }
        }
            return toRet;
     }
     catch (Exception e)
     {//Catch exception if any
            System.err.println("Error: " + e.getMessage());
     } 
     return null;
}
4

3 に答える 3

7

ファイルを Jar ファイル内の「ファイル」として検索しようとしないでください。代わりにリソースを使用してください。

クラスまたはクラス ローダーへの参照を取得してから、クラスまたはクラス ローダーの呼び出しを取得しますgetResourceAsStream(/* resource address */);


以下の同様の質問を参照してください (可能であれば、新しい質問を作成しないでください)。

于 2012-05-04T16:38:36.050 に答える
3
// add a leading slash to indicate 'search from the root of the class-path'
URL urlToDictionary = this.getClass().getResource("/" + "Dictionary.txt");
InputStream stream = urlToDictionary.openStream();

この回答も参照してください。

于 2012-05-04T16:43:21.617 に答える
2

この質問の正確な複製のようです: How do I access a config file inside the jar?

に関するあなたの問題に加えてNullPointerException、それが起こらないことを確認するのではなく、準備をして適切に処理することをお勧めします。さらに、変数の null 値を常にチェックするようにお願いしたいと思います。これは良いことです。

于 2012-05-04T16:40:42.653 に答える