getClass().getResourceAsStream(fname)
で端末からのclassファイルの実行では同じディレクトリから、jarファイルのダブルクリックでの実行ではjarファイルの中から fname(文字列)で指定されているファイルを見つけてInputStreamを得る。
Mondaishuu.java を少しだけ変更するだけだが、Mondaishuuj.java をそのまま残したいので、名前を MondaishuujI.java にする。この色の部分は動作テストのためだけに加えてあるので動作には必要ない。
public MondaishuuI( String fname, int toimax ){ toi = new Toi[toimax]; seikaict=0; gotouct =0; int ct =0; try { System.out.println("The class of "+this+ " is " + this.getClass().getName()); System.out.println("The URL of "+this+ " is " + this.getClass().getResource(fname)); InputStream is = getClass().getResourceAsStream(fname); InputStreamReader in = new InputStreamReader(is); BufferedReader inb = new BufferedReader(in);
SanTakF.java は、MondaishuuI.java のインスタンスを使うというだけの変更だが、SanTakI.java とする。
MondaishuuI m; /* コンストラクタ*/ public SanTakuI(){ setDefaultCloseOperation(EXIT_ON_CLOSE); //終了処理を追加 String fname = "mondai.txt"; m = new Mondaishuuj(fname,10);
jarファイルには mondai.txt を入れた。
~/java$ jar cvfm SanTakuI.jar SanTakuI.txt SanTakuI.class MondaishuuI.class Toi.class mondai.txt
jarにするとSystem.out.printlnの出力テキストは.xsession-errorsに入る。
getClass().getName() と getClass().getResource(fname))の出力
java ディレクトリに置いたjarを実行したとき。
~/java$ cat ../.xsession-errors The class of MondaishuuI@5740bb is MondaishuuI The URL of MondaishuuI@5740bb is jar:file:/home/z1c3s/java/SanTakuI.jar!/mondai.txt -0 -1 読込終了。
ユーザーホームディレクトリに置いたjarを実行したとき。
The class of MondaishuuI@1bf73fa is MondaishuuI The URL of MondaishuuI@1bf73fa is jar:file:/home/z1c3s/SanTakuI.jar!/mondai.txt -0 -1 読込終了。
Classのマニュアルの記述
java.lang クラス Class<T> URL getResource(String name) 指定された名前のリソースを探します。 InputStream getResourceAsStream(String name) 指定された名前のリソースを探します。
Objectのマニュアルの記述
java.lang クラス Object Class<?> getClass() この Object の実行時クラスを返します。
public void loadImage(String filename) { try { //File f = new File(filename); //image = ImageIO.read(f); image = ImageIO.read(getClass().getResource(filename)); } catch (IOException e) { e.printStackTrace(); } }