简体   繁体   中英

What's wrong with this code in java that uses FileReader?

I have been trying to learn about FileReader and hence wanted to test it out. I created a class whose constructor takes in a string(name of the file) and creates a file and then reads from it and then prints the first character out, but my code is not working and is showing errors. This is my java code.

package test_3;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class Files {
    public Files(String s) throws FileNotFoundException, IOException{
        File f = new File(s);
        FileReader fr = new FileReader(f);
        System.out.println(fr.read());
    }

    public static void main(String args[]) throws FileNotFoundException,   IOException{
        Files myFile = new Files("input.txt");
    }
}

This is the error information

Exception in thread "main" java.io.FileNotFoundException: input.txt (The system cannot find the file specified)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(Unknown Source)
    at java.io.FileInputStream.<init>(Unknown Source)
    at java.io.FileReader.<init>(Unknown Source)
    at test_3.Files.<init>(Files.java:11)
    at test_3.Files.main(Files.java:16)

Because the file cannot be found. What you should do is get the path to where java is looking for the file, like so.

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

And then place "input.txt" within that directory (the directory that is printed when that code is ran).

Alternatively, use the full absolute path to input.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM