アプリのjarファイルと同じディレクトリにあるファイルの名前を引数として取得して、そこから読み取ることができる単純なコマンドラインJavaアプリを作成したいと思います。ただし、FileNotFoundException が発生します。ここに私のコードがあります:
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("Give the name of the input file as argument.");
} else if (args.length > 1) {
System.out.println("Only one input file is allowed");
} else {
try {
BufferedReader in = new BufferedReader(new FileReader(args[0]));
System.out.println("File found");
} catch (FileNotFoundException e) {
System.out.println("Could not find file " + args[0]);
}
}
}
したがって、同じディレクトリ内に a.txt という名前の txt ファイルと myApp.jar ファイルがあるとします。cmd と cd を開始して、この特定のディレクトリに移動し、次のように入力します。
java -jar myApp.jar a.txt
そして、「ファイルa.txtが見つかりませんでした」というメッセージが表示されます
私は何を間違っていますか?
編集:考えた後、クラスファイルと同じディレクトリ、つまりjar内にある必要があるため、ファイルが見つからないと思います。だから私の質問は、それがjarファイルの外にあるときにどのようにアクセスできるのですか?