こんにちは、パスを指定せずに FileInputStream をhello.txt
同じディレクトリに読み込む方法はありますか?
package hello/
helloreader.java
hello.txt
私のエラーメッセージ:Error: .\hello.txt (The system cannot find the file specified)
こんにちは、パスを指定せずに FileInputStream をhello.txt
同じディレクトリに読み込む方法はありますか?
package hello/
helloreader.java
hello.txt
私のエラーメッセージ:Error: .\hello.txt (The system cannot find the file specified)
のような相対パスでファイルを読み取ることができます。
File file = new File("./hello.txt");
あなたのプロジェクト
->ビン
->hello.txt
->.classpath
->.project
作品はこちら
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class fileInputStream {
public static void main(String[] args) {
File file = new File("./hello.txt");
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
System.out.println("Total file size to read (in bytes) : "
+ fis.available());
int content;
while ((content = fis.read()) != -1) {
// convert to char and display it
System.out.print((char) content);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
を使用できますYourClassName.class.getResourceAsStream("Filename.txt")
が、テキスト ファイルはファイルと同じディレクトリ/パッケージにある必要がありYourClassName
ます。
「hello.txt」を開くと、プロセスの現在の作業ディレクトリにあるファイルが開かれます。つまり、jar の場所やその他のディレクトリではなく、プログラムが実行された場所です。
hello.txt
pathでファイルを開くと、ファイルはコマンドhello.txt
を実行した場所と同じディレクトリjava
、つまり作業ディレクトリにある必要があります。また、次のコードを使用して、Java プログラムの実行時に作業ディレクトリを出力できます。
System.out.println(System.getProperty("user.dir"));
この のようにコードを実行すると仮定するとjava hello.helloreader
、次のパスを使用して を取得する必要がありますhello.txt
。
new FileInputStream("hello/hello.txt")
System.getProperty("dir") を試して現在のディレクトリを表示すると、ファイルパスの書き方がわかります