Reputation: 169
I wrote a sample text in the notebook. Then I saved the file on the desktop by calling it TEST. When I try to read its contents, unfortunately in the following code I receive the message: "The file can not be opened". What could I do to read the text from the TEST file?
This is my code:
public static void main(String[] args) {
int i;
FileInputStream fin;
//Checks whether the file name was specified
if(args.length !=1) {
System.out.println("Usage: ShowFile TEST.TXT");
return;
}
//Try open
try {
fin = new FileInputStream(args[0]);
} catch(FileNotFoundException exc) {
System.out.println("The file can not be opened!");
return;
}
//At this stage, the file is open and ready to read, the following code reads the characters to reach the end of the file
try {
do {
i = fin.read();
if(i != -1) System.out.println((char)i);
} while(i != -1);
} catch (IOException exc) {
System.out.println("Error reading the file");
}
//Close file
try {
fin.close();
} catch(IOException exc) {
System.out.println("Error close file!");
}
}
On the command line i wrote: TEST.TXT
Upvotes: 1
Views: 68
Reputation: 292
Of course You would get an Error.! Because by default FileInputStream() would check for the file in the current directory i.e in the directory where your java source file is located. And as you have saved your TEST.TXT on your Desktop.
So to open your file located in Desktop folder. Just provide the absolute path of your file to the FileInputStream.
For example, if file is stored at C:\Users\user\Desktop\TEST.txt
then
file = new FileInputStream("C:\Users\user\Desktop\TEST.txt");
Thankyou and Happy coding..!
Upvotes: 3
Reputation: 109547
That is because not the full path is given, and the working directory is the taken as starting directory. That path is in System.getProperty("home.dir")
.
Path path = Paths.get("TEST.txt");
System.out.println("Full path: " + path.toAbsolutePath());
You might use for the desktop:
System.getProperty("home.user") + "/Desktop/" + args[0]
Upvotes: 1
Reputation: 721
Try this
BufferedReader br = new BufferedReader(new FileReader(new File("TEST")));
Sytem.out.println(br.readLine());
Upvotes: 3