java - java中的文件处理

标签 java file-handling

我有以下代码。

以下源代码来自文件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();
        }

    }

}

最佳答案

.java文件的目录不一定是你代码运行的方向!您可以通过以下示例检查程序的当前工作目录:

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

您可以使用 System.getProperty( "user.dir") 字符串使您的相对文件名成为绝对文件名!只需将其作为您的文件名的前缀:)

关于java - java中的文件处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6269406/

相关文章:

java - 遍历实例变量的 ArrayList

java - Listview 的 onclick 事件问题

java - Spring 3 的最佳 View 层是什么?

java - 在java中分析mp3文件的fft

java - 支持或反对使用 JVM 的主要论点

c++ - 如何在 C++ 中的给定路径中创建目录?

swift - 如果文件不存在,如何在文档文件夹中创建文件?

java - 在java中打印文本文件引号内的一行

c# - 使用 C# 读取文件的创建最后修改时间戳

c++ - 为什么 tellp() 为 ios::app 返回 0 而不是为 ios::ate?