2

私は以下のコードを持っています。

以下のソースコードは、ファイルx.javaからのものです。hi.htmlは、x.javaと同じディレクトリにあります。

ファイルが存在していても、ファイルが見つからないという例外が発生します。私は何かが足りないのですか?

    public void sendStaticResource() throws IOException{
    byte[] bytes = new byte[1024];
    FileInputStream fis = null;

    try{
        File file = new File("hi.html");

        boolean p  = file.exists();

        int i = fis.available();

        fis = new FileInputStream(file);

        int ch = fis.read(bytes, 0, 1024);

        while(ch!=-1){
            output.write(bytes, 0, ch);
            ch = fis.read(bytes, 0, 1024);
        }

    }catch(Exception e){
        String errorMessage = "file not found";
        output.write(errorMessage.getBytes());
    }finally {
        if(fis != null){
            fis.close();
        }

    }

}
4

6 に答える 6

4

.java ファイルのディレクトリは、必ずしもコードが実行される方向とは限りません! 次の例では、プログラムの現在の作業ディレクトリを確認できます。

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

System.getProperty( "user.dir" ) 文字列を使用して、相対ファイル名を絶対的なものにすることができます! ファイル名の前に付けるだけです:)

于 2011-06-07T17:46:01.050 に答える
3

「user.dir」プロパティを見てください。

String curDir = System.getProperty("user.dir");

これは、プログラムが完全なパスを持たないファイルの検索を開始する場所です。

于 2011-06-07T17:45:51.530 に答える
0

私はあなたが得ると思いますNullPointerException

FileInputStream fis = null;

次に呼び出し:

int i = fis.available();

NullPointerExceptionへの最初の非 null 割り当てfisが後であるため、結果は次のようになります。

fis = new FileInputStream(file);
于 2011-06-07T18:14:16.537 に答える
0
  • Exception をキャッチする前に FileNotFoundException をキャッチして、それが実際の Exception タイプであることを確認します。
  • ファイルの絶対的な場所を指定しないため、作業ディレクトリから検索されます。絶対パスをプロパティ ファイルに格納し、代わりにそれを使用するかSystem.getProperty("user.dir")、Java アプリを実行しているディレクトリを返すために使用できます。

プロパティ ファイルから Key-Value を取得するコード

private void getPropertyFileValues() {
    String currentPath = System.getProperty("user.dir") + System.getProperty("file.separator") + "Loader.properties";
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(currentPath);
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    }
    Properties props = new Properties();
    try {
        props.load(fis);
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    String filePath= props.getProperty("FILE_PATH");
    try {
        fis.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}
于 2011-06-07T18:10:06.230 に答える