6

こんにちは、パスを指定せずに FileInputStream をhello.txt同じディレクトリに読み込む方法はありますか?

package hello/
    helloreader.java
    hello.txt

私のエラーメッセージ:Error: .\hello.txt (The system cannot find the file specified)

4

5 に答える 5

11

のような相対パスでファイルを読み取ることができます。

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();
            }
        }
    }
}
于 2012-09-13T12:46:51.690 に答える
9

を使用できますYourClassName.class.getResourceAsStream("Filename.txt")が、テキスト ファイルはファイルと同じディレクトリ/パッケージにある必要がありYourClassNameます。

于 2012-09-13T12:35:39.420 に答える
4

「hello.txt」を開くと、プロセスの現在の作業ディレクトリにあるファイルが開かれます。つまり、jar の場所やその他のディレクトリではなく、プログラムが実行された場所です。

于 2012-09-13T12:38:23.727 に答える
3

hello.txtpathでファイルを開くと、ファイルはコマンドhello.txtを実行した場所と同じディレクトリjava、つまり作業ディレクトリにある必要があります。また、次のコードを使用して、Java プログラムの実行時に作業ディレクトリを出力できます。

System.out.println(System.getProperty("user.dir"));

この のようにコードを実行すると仮定するとjava hello.helloreader、次のパスを使用して を取得する必要がありますhello.txt

new FileInputStream("hello/hello.txt")
于 2012-09-13T12:47:59.747 に答える
0

System.getProperty("dir") を試して現在のディレクトリを表示すると、ファイルパスの書き方がわかります

于 2012-09-13T12:47:49.443 に答える