This question already has answers here:
FileNotFoundException, the file exists Java [closed]
(2 answers)
Closed 7 years ago.
Hello I have this in my code
File file = new File("words.txt");
Scanner scanFile = new Scanner(new FileReader(file));
ArrayList<String> words = new ArrayList<String>();
String theWord;
while (scanFile.hasNext()){
theWord = scanFile.next();
words.add(theWord);
}
But for some reason I am getting a
java.io.FileNotFoundException
I have the words.txt file in the same folder as all of my .java files
What am I doing wrong? Thanks!
Tip: add this line to your code...
System.out.println(file.getAbsolutePath());
Then compare that path with where your file actually is. The problem should be immediately obvious.
The file should reside in the directory from which you execute the application, i.e. the working directory.
Generally it's a good idea to package data files with your code, but then using java.io.File to read them is a problem, as it's hard to find them. The solution is to use the getResource() methods in java.lang.ClassLoader to open a stream to a file. That way the ClassLoader looks for your files in the location where your code is stored, wherever that may be.
try:
URL url = this.getClass().getResource( "words.txt" );
File file = new File(url.getPath());
You haven't specified an absolute path. The path would therefore be treated as a path, relative to the current working directory of the process. Usually this is the directory from where you've launched the Main-Class.
If you're unsure about the location of the working directory, you can print it out using the following snippet:
System.out.println(System.getProperty("user.dir"));
Fixing the problem will require adding the necessary directories in the original path, to locate the file.
Related
I've been trying to set up a Scanner to use a File as an input, but it doesn't seem to recognize the filepath. The file exists in the same folder as my .java files.
File errorList = new File("Errors.txt");
Scanner errorIn = new Scanner(errorList);
This results in a FileNotFoundException.
What am I doing wrong, and how can I fix this?
One other approach you could try is, execute the below code in your eclipse (from any of your class), and see where the hello.txt is created, so you get an idea of where Java is looking for the file.
new File("hello.txt").createNewFile();
Then you could either put your Errors.txt in that location or provide the corresponding relative location.
This question already has answers here:
How to get the real path of Java application at runtime?
(15 answers)
Closed 6 years ago.
I'm trying to load a .txt file into an arrayList in java using a combination of relative paths.
My jar file is in /usr/tool/dist/tool.jar
The file I want to load is in /usr/tool/files/file.txt
I think I was able to retrieve the path of my tool.jar, but how can I go from that path to the one where my file is?
I have the following code
// String path should give me '/usr/tool'
File f = new File(System.getProperty("java.class.path"));
File dir = f.getAbsoluteFile().getParentFile();
String path = dir.toString();
String table1 = this should represent /usr/tool/files/file.txt
BufferedReader buf_table1 = new BufferedReader(new FileReader(new File(table1)));
To find the path of your jar file being executed, java.class.path is not the right property. This property may contain more than one file, and you cannot know which is the right one. (See the docs.)
To find the path of the correct jar file, you can use this instead:
URL url = MainClass.class.getProtectionDomain().getCodeSource().getLocation().getPath();
Where MainClass the main class of your tool, or any other class in the same jar file.
Next, the parent File of a file is its directory. So the parent File of /usr/tool/dist/tool.jar is /usr/tool/dist/. So if you want to get to /usr/tool/files/file.txt, you need to get the parent of the parent, and then from there files/file.txt.
Putting it together:
File jarFile = new File(MainClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());
File file = new File(jarFile.getParentFile().getParent(), "files/file.txt");
This question already has answers here:
java.io.FileNotFoundException: the system cannot find the file specified
(8 answers)
Closed 4 years ago.
My program get a filename in parameter but if i want to use it i need the full directory path or i get filenotfoundexception.
For example:
My program got sample.txt in parameter from C:\Users\me\documents.
File file = new File(args[0]);
FileReader fr = new FileReader(file);
That throw filenotfoundexception.
So what should i use to locate the file?
I saw so many similar question but i didnt find solution :(
I tried to use getResources and getPath but nothing.
You can open a file with just the filename if that file exists in the same directory as of your source code. If the file is located at any random location then you need to give the complete path of the file along with its name.
Eg: c:\documents\sample.txt
Or another thing that you can try is recursively going through all folders present in your file system and locate the file. However, this is will be a very horrible solution.
File fileName = new File("myfile.txt");
if(!fileName.exists()) {
fileName.createNewFile();
}
FileOutputStream oFile = new FileOutputStream(fileName, false);
add this code if your file is not on the location this will create a one for you then you wont be getting filenotfound exception at the latter part
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?
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.
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
You need to give the absolute pathname to where the file exists.
File file = new File("C:\\Users\\User\\Documents\\Workspace\\FileRead\\hello.txt");
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"
Generally, just stating the name of file inside the File constructor means that the file is located in the same directory as the java file. However, when using IDEs like NetBeans and Eclipse i.e. not the case you have to save the file in the project folder directory. So I think checking that will solve your problem.
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.
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.);
}
When you run a jar, your Main class itself becomes args[0] and your filename comes immediately after.
I had the same issue: I could locate my file when provided the absolute path from eclipse (because I was referring to the file as args[0]). Yet when I run the same from jar, it was trying to locate my main class - which is when I got the idea that I should be reading my file from args[1].
I think I am really close, but I am unable to open a file I have called LocalNews.txt. Error says can't find file specified.
String y = "LocalNews.txt";
FileInputStream fstream = new FileInputStream(y);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
Name of file is LocalNews.txt in library called News....anyone know why the file will not open?
The file is in the same Java Project that I am working on.
Error: LocalNews.txt (The system cannot find the file specified)
Project is named Bst, package is src in subPackage newsFinder, and library that the text files are stored in is called News.
Found out it was looking in
C:\EclipseIndigoWorkspace1\Bst\bin\LocalNews.txt
But I want it to look in (I believe)
C:\EclipseIndigoWorkspace1\Bst\News\LocalNews.txt
But if I make the above url a string, I get an error.
String y = "LocalNews.txt";
instead use
String y = "path from root/LocalNews.txt"; //I mean the complete path of the file
Your program can probably not find the file because it is looking in another folder.
Try using a absolute path like
String y = "c:\\temp\\LocalNews.txt";
By 'library called News' I assume you mean a jar file like News.jar which is on the classpath and contains the LocalNews.txt file you need. If this is the case, then you can get an InputStream for it by calling:
InputStream is = Thread.currentThread().getContextClassLoader()
.getResourceAsStream("LocalNews.txt");
Use
System.out.println(System.getProperty("user.dir") );
to find out what your current directory is. Then you'll know for sure whether your file is in the current directory or not. If it is not, then you have to specify the path so that it looks in the right directory.
Also, try this -
File file = new File (y);
System.out.println(file.getCanonicalPath());
This will tell you the exact path of your file on the system, provided your file is in the current directory. If it does not, then you know your file is not in the current directory.