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){
You need to give the absolute pathname to where the file exists.
File file = new File("C:\\Users\\User\\Documents\\Workspace\\FileRead\\hello.txt");
How are you running the program?
It's not the java file that is being ran but rather the .class file that is created by compiling the java code. You will either need to specify the absolute path like user1420750 says or a relative path to your System.getProperty("user.dir")
directory. This should be the working directory or the directory you ran the java command from.
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
In your IDE right click on the file you want to read and choose "copy path" then paste it into your code.
Note that windows hides the file extension so if you create a text file "myfile.txt" it might be actually saved as "myfile.txt.txt"
First Create folder same as path which you Specified. after then create File
File dir = new File("C:\\USER\\Semple_file\\");
File file = new File("C:\\USER\\Semple_file\\abc.txt");
if(!file.exists())
{
dir.mkdir();
file.createNewFile();
System.out.println("File,Folder Created.);
}
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.