I have a program that scans a file and then closes the file.
import java.util.*;
import java.io.*;
public class FileTester{
public static void main(String[] args) throws IOException {
File test = new File("MyDatta.in.txt");
Scanner sf = new Scanner(test);
sf.close();
}
}
When I run the program I get an error message like this:
Exception in thread "main" java.io.FileNotFoundException: MyDatta.in.txt (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:120)
at java.util.Scanner.<init>(Scanner.java:636)
at FileTester.main(FileTester.java:6)
I have a mac that runs on Mac OS. I have reason to believe it has to do with the pathway to my file which is in documents. I know in windows one would use C:\folder name\file to scan it but I just don't know with Mac and I cannot find it anywhere
From Java documentation for FileInputStream: "If the named file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading then a FileNotFoundException is thrown."
Maybe file is used by another program?
You should put this as the file path:
~/Documents/MyDatta.in.txt
to tell java that your file is in documents. The ~ is your home folder.
Related
I am attempting to read from a file, however the console gives me this error.
Exception in thread "main" java.io.FileNotFoundException: dataEx.txt (The system cannot find the file specified)
This is the code that I am executing.
import java.io.*;
import java.util.*;
public class ReadTest {
public static void main(String[] args) throws IOException {
BufferedReader f = new BufferedReader(new FileReader("dataEx.txt" ));
}
}
This is my project structure
-project
-ReadTest.java
-dataEx.txt
Working directory
Your path is wrong, thus the reader can not find the file. Whereever you think your current working directory should be, that is not where it is.
Execute the following code to know where it is:
System.out.println(Paths.get("").toAbsolutePath());
That is the path to your current working directory. Then compare that result to your expectation. Realize that your expectation was wrong and correct the path to your file or your working directory settings.
It is hard to guess where your directory might be right now. Maybe in your bin folder, next to the .class files. You will see after executing the above code snippet.
NIO
By the way, not sure what exactly you plan on doing with that BufferedReader but you might be interested in the newer modern file API revolving around Files and Paths:
List<String> lines = Files.readAllLines(Paths.get("myFile.txt"));
It also has other neat utility methods for File IO, much better than the cumbersome File class and the clunky BufferedReader.
This code throws FileNotFoundException.
Edit: As requested I have included the full StackTrace.
import java.io.FileInputStream;
import java.io.InputStream;
public class ReadFile{
public static void main(String[] args){
InputStream inputstream = new FileInputStream("C:\\file.txt");
}
}
The file "file.txt" is at that location though. I would like to post a screenshot of this as requested, but I can't because I need at least 10 reputation points.
If you are 100% certain that the file exists and you're still getting a FileNotFoundException, than most likely your user or the user running Java has no permission to access this file (since I am using German Windows the dialog is in German, but as you can see "Benutzer" (which is Users) have a denied right to read and execute the file a.txt:
This however, results in a a FileNotFoundException with a localized error message returned :
Exception in thread "main" java.io.FileNotFoundException: C:\a.txt (Zugriff verweigert)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:131)
at java.io.FileInputStream.<init>(FileInputStream.java:87)
at Threadstuff.main(Threadstuff.java:50)
Zugriff verweigert means "access denied". If that isn't the problem either, I guess you should post your full StackTrace.
The other option I mentioned in my comment is an explorer option ("View" -> "Options") in the Folder and Search options -> View:
(roughly translates to "Hide extensions for known extensions")
If this is enabled, the filenames in the explorer are losing their extensions in the view. Meaning that they are shown as "file" instead of "file.txt" - which sometimes leads to the mistake of creating a "file.txt.txt" when renaming a file. And is/was also often used to trick users into thinking they were open a different kind of file (.pdf.exe) - mostly used by bad guys.
Is this really the full Filepath? Better check that one.
Also I'd recommend putting files that are to be read by your program e.g. Textfiles, Images and such into the classpath of your project so when you pack and export it the file paths are not obstructed by being on somebody else's PC where that file does not exist on that path and so on.
This answer suggest you transform the Path of the file to a java conform URL path.
Try the below one.
InputStream inputstream = new FileInputStream("C:"+File.separator+"file.txt");
A better approach would be
File file = new File("C:"+File.separator+"file.txt");
if(file.exists()) {
//Read the file
}
else {
System.out.println("File does not exist);
}
To ensure whether file exists or not in windows, press windows button + r and then paste the file path you have mentioned and after that press enter key. If file is in that location, a notepad with file contents will be opened.
Why the program search the file:
File FILE_PATH = new File("C:\\Users\\home\\Desktop\\DbWord.txt");
System.out.println(FILE_PATH.exists());
System.out.println(FILE_PATH.getAbsoluteFile());
FileInputStream fIn = new FileInputStream(FILE_PATH);
Scanner reader = new Scanner(fIn);
at: C:\Users\home\Documents\NetBeansProjects\MyDatabase\C:\Users\home\Desktop\DbWord.txt
How can i counteract the default location?
If something in this post not good, please tell me and no negative vote.
Thanks!
why negative votes??????????????? whats your problems??????????
Please double check your error details. You might have seen something like the below error. Actually the program is not searching for the file "C:\Users\home\Documents\NetBeansProjects\MyDatabase\C:\Users\home\Desktop\DbWord.txt", it is trying to locate the file "C:\Users\home\Desktop\DbWord.txt" which does not exists in your machine. You are seeing "C:\Users\home\Documents\NetBeansProjects\MyDatabase\C:\Users\home\Desktop\DbWord.txt" along with the error because you have already used System.out.println(FILE_PATH.getAbsoluteFile()); statement in your code.
false
Exception in thread "main" java.io.FileNotFoundException: C:\Users\home\Desktop\DbWord.txt (The filename, directory name, or volume label syntax is incorrect)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
C:\Users\home\Documents\NetBeansProjects\MyDatabase\C:\Users\home\Desktop\DbWord.txt
at com.stackoverflow.answer.SimpleFileHelper.main(SimpleFileHelper.java:17)
Hope you are clear now.
There are three main chances where a FileNotFoundException may be thrown.
The named file does not exist.
The named file is actually a directory not file.
The named file cannot be opened for reading due to some reason.
The first two reasons are unlikely based on your description, please check the third point using file.canRead() method.
If the test above returns true, I would suspect the following:
You might have forgotten to explicitly throw or catch the potential exception (i.e., FileNotFoundExcetion). If you work in an IDE, you should have got some complaint from the compiler. But I suspect you didn't run your code in such an IDE.
Try the following code and see if the exception would be gone:
package com.stackoverflow.answer;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class SimpleFileHelper {
public static void main(String[] args) throws FileNotFoundException {
File FILE_PATH = new File("C:/Users/home/Desktop/DbWord.txt");
System.out.println(FILE_PATH.exists());
System.out.println(FILE_PATH.getAbsoluteFile());
FileInputStream fIn = new FileInputStream(FILE_PATH);
Scanner reader = new Scanner(fIn);
}
}
I was trying to make a directory and file using java with File object as:
import java.io.*;
class CreateFile{
public static void main(String[] args) throws IOException{
File f = new File("File/handling/file1.txt");
if(!f.exists())
f.createNewFile();
}
}
but its showing error (see below) and unable to make it, the path and file name doesn't existed before execution. I don't know where am I going wrong, someone please clarify whats the mistake and how to resolve it? It might be I need to know something about File object, so please do tell me...
See error:
Exception in thread "main" java.io.IOException: The system cannot find the path
specified
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:947)
at CreateFile.main(CreateFile.java:6)
The error is telling you that either there is no File directory relative to where you're running this, or there is but it doesn't have a handling subdirectory. In this case, exists returns false and so you call createNewFile to try to create the file, but the directory in which you're trying to create it doesn't exist, and so it throws an exception.
You can use mkdirs to create the directories if necessary, like so:
import java.io.*;
class CreateFile{
public static void main(String[] args) throws IOException{
File f = new File("File/handling/file1.txt");
if(!f.exists()) {
f.getParentFile().mkdirs(); // This is a no-op if it exists
f.createNewFile();
}
}
}
this is my first time posting on stackoverflow. I have a question about a series of errors that I have been encountering when I try to read in data from a generic text file in Netbeans IDE 7.4. I am using a 2009 iMac with Mac OS X Mavericks.
import java.util.Scanner;
import java.io.File;
public class two {
public static void main(String[] args) throws Exception
{
System.out.println("Directory: "+System.getProperty("user.dir"));
File f = new File("newfile.dat");
Scanner s = new Scanner(f);
}
}
And this code will return this set of errors:
Directory: /Users/omavine/Desktop/aPlusComputerScience
Exception in thread "main" java.io.FileNotFoundException: newfile.dat (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:143)
at java.util.Scanner.<init>(Scanner.java:656)
at apluscomputerscience.two.main(two.java:22)
at apluscomputerscience.APlusComputerScience.main(APlusComputerScience.java:21)
Java Result: 1
This would indicate to me that the file simply was not being searched for in the correct path, however, when I compare the filename with the absolute path:
System.out.println("Directory: "+System.getProperty("user.dir"));
File f = new File("newfile.dat");
System.out.println("Path: "+f.getAbsolutePath());
Then the output is as follows:
Directory: /Users/omavine/Desktop/aPlusComputerScience
Path: /Users/omavine/Desktop/aPlusComputerScience/newfile.dat
Which would indicate (to me) that the file is being searched for in the correct place whether I look for it with the explicit pathname or not.
However, when I try to construct the Scanner, (even with the absolute pathname):
Directory: /Users/omavine/Desktop/aPlusComputerScience
Path: /Users/maven/Desktop/aPlusComputerScience/newfile.dat
Exception in thread "main" java.io.FileNotFoundException: /Users/omavine/Desktop/aPlusComputerScience/newfile.dat (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:143)
at java.util.Scanner.<init>(Scanner.java:656)
at apluscomputerscience.two.main(two.java:23)
at apluscomputerscience.APlusComputerScience.main(APlusComputerScience.java:21)
Java Result: 1
Still the same error. Interestingly enough, attempting to construct the scanner by using:
File f = new File("newfile.dat");
Scanner s = new Scanner(f.getClass().getResourceAsStream("newfile.dat"));
Returns:
Directory: /Users/omavine/Desktop/aPlusComputerScience
Path: /Users/omavine/Desktop/aPlusComputerScience/newfile.dat
Exception in thread "main" java.lang.NullPointerException
at java.io.Reader.<init>(Reader.java:78)
at java.io.InputStreamReader.<init>(InputStreamReader.java:72)
at java.util.Scanner.<init>(Scanner.java:608)
at apluscomputerscience.two.main(two.java:23)
at apluscomputerscience.APlusComputerScience.main(APlusComputerScience.java:21)
Java Result: 1
(Reading in the file with the getClass().getResourceAsStream() seems to return a null pointer exception, for whatever reason.)
I'd like to be able to read files on my home computer. This type of scenario has never happened to me at other computers with JCreator IDE. Can anyone make heads or tails of this dilemma?
the output clearly indicates you are looking at different directories.
Directory: /Users/omavine/Desktop/aPlusComputerScience
Path: /Users/maven/Desktop/aPlusComputerScience/newfile.dat
the working directory is in omavine's desktop. your file is in maven's desktop.
Instead of giving the relative path, try giving the actual path of the file.
File f = new File("/Users/maven/Desktop/aPlusComputerScience/newfile.dat");
this ought to work.
EDIT: about the NullPointerException for getResourceAsStream
the java API doc statest that
Returns:
An input stream for reading the resource, or null if the resource could not be found
and the Scanner throws the NullPointerException.
refer javadocs