Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The system cannot find the file specified in java

Tags:

I am making a program that opens and reads a file. This is my code:

import java.io.*;

public class FileRead{
    public static void main(String[] args){
        try{
            File file = new File("hello.txt");
            System.out.println(file.getCanonicalPath());
            FileInputStream ft = new FileInputStream(file);

            DataInputStream in = new DataInputStream(ft);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strline;

            while((strline = br.readLine()) != null){
                System.out.println(strline);
            }
            in.close();
        }catch(Exception e){
            System.err.println("Error: " + e.getMessage());
        }
    }
}

but when I run, I get this error:

C:\Users\User\Documents\Workspace\FileRead\hello.txt
Error: hello.txt (The system cannot find the file specified)

my FileRead.java and hello.txt where in the same directory that can be found in:

C:\Users\User\Documents\Workspace\FileRead

I'm wondering what I am doing wrong?

like image 619
gadss Avatar asked Jul 19 '12 02:07

gadss


People also ask

How do I fix Java file not found?

If it isn't (which is strange in and of itself), you need to run javac from where it's located, but navigate to the exact location of your Java class file in order to compile it successfully. By default, javac will compile a file name relative to the current path, and if it can't find the file, it won't compile it.

How do you fix the system Cannot find the file specified error?

Use SFC to fix system cannot finds the file specified error. In Command Prompt, type the following command: “sfc /scannow”. Now press Enter. After scanning and correcting errors, restart the computer and check if the “system cannot find the file specified” error is fixed.

How do I find the path of a file in Java?

In Java, for NIO Path, we can use path. toAbsolutePath() to get the file path; For legacy IO File, we can use file. getAbsolutePath() to get the file path.


2 Answers

Try to list all files' names in the directory by calling:

File file = new File("."); for(String fileNames : file.list()) System.out.println(fileNames); 

and see if you will find your files in the list.

like image 105
Eng.Fouad Avatar answered Sep 16 '22 20:09

Eng.Fouad


I have copied your code and it runs fine.

I suspect you are simply having some problem in the actual file name of hello.txt, or you are running in a wrong directory. Consider verifying by the method suggested by @Eng.Fouad

like image 37
Adrian Shum Avatar answered Sep 20 '22 20:09

Adrian Shum