FileInputStream示例,I / O错误:找不到文件

时间:2016-01-14 16:28:09

标签: java file io filenotfoundexception

我正在从书中做例子

  

“Java The Complete Reference Ninth Edition”

使用try-with资源演示FileInputStream。 在输出中我得到了"I/O Error: java.io.FileNotFoundException: C:\Users\user\Documents\NetBeansProjects\JavaExam\FileInputStreamDemo.java (Can't find file)"。 代码:

package javaexam;
import java.io.*;

class FileInputStreamDemo {
    public static void main(String args[]) {
        int size;

        // Use try-with-resources to close the stream.
        try ( FileInputStream f = 
                new FileInputStream("C:\\Users\\user\\Documents\\NetBeansProjects\\JavaExam\\FileInputStreamDemo.java"))  
        {

            System.out.println("Total Available Bytes: " + (size = f.available()));
            int n = size/40;
            System.out.println("First " + n + " bytes of the file one read() at a time");
            for (int i = 0; i < n; i++) {
                System.out.print((char) f.read());
            }
            System.out.println("\nStill Available: " + f.available());
            System.out.println("Reading the next " + n + " with one read(b[])");
            byte b[] = new byte[n];
            if (f.read(b) != n) {
                System.err.println("couldn't read " + n + " bytes.");
            }
            System.out.println(new String(b, 0, n));
            System.out.println("\nStill Available: " + (size = f.available()));
            System.out.println("Skipping half of remaining bytes with skip()");
            f.skip(size/2);
            System.out.println("Reading " + n/2 + " into the end of array");
            if (f.read(b, n/2, n/2) != n/2) {
                System.err.println("couldn't read " + n/2 + " bytes.");
            }
            System.out.println(new String(b, 0, b.length));
            System.out.println("\nStill Available: " + f.available());
        } catch (IOException e) {
            System.out.println("I/O Error: " + e);
        }
    }
}

2 个答案:

答案 0 :(得分:0)

我认为您的问题可能是您正在使用反斜杠。不过,我不确定。请尝试使用BufferedReader。

File file = new File("C:/Users/user/Documents/NetBeansProjects/JavaExam/FileInputStreamDemo.java");
BufferedReader bufferedreader = new BufferedReader(new FileReader(file));

使用它你应该能够更容易地读取它,并逐行而不是逐字节地读取它。

答案 1 :(得分:0)

您正在查找的文件应位于包src下的javaexam文件夹中。否则将无法编译。根据Java约定,每个public类应该具有该文件的名称,并且位于具有包名称的文件夹中。

new FileInputStream("C:\\Users\\user\\Documents\\NetBeansProjects\\JavaExam\\src\\javaexam\\FileInputStreamDemo.java"))