Java - FilenotfoundException for reading text file - java

by running this...
File file = new File("Highscores.scr");
i keep getting this error, and i really don't know how to get around it.
the file is currently sitting in my source packages with my .java files.
I can quite easily read the file by specifying the path but i intend to run this on multiple computers so i need the file to be portable with the program.
this question isnt about reading the text file but rather specifying its location without using an absolute path .
ive searched for the answer but the answers i get are just "specify the name" and "specify the absolute path".
id post an image to make it more clear but i dont have the 10 rep to do so :/
how do i do this?
cheers.

The best way to do this is to put it in your classpath then getResource()
package com.sandbox;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
public class Sandbox {
public static void main(String[] args) throws URISyntaxException, IOException {
new Sandbox().run();
}
private void run() throws URISyntaxException, IOException {
URL resource = Sandbox.class.getResource("/my.txt");
File file = new File(resource.toURI());
String s = FileUtils.readFileToString(file);
System.out.println(s);
}
}
I'm doing this because I'm assuming you need a File. But if you have an api which takes an InputStream instead, it's probably better to use getResourceAsStream instead.
Notice the path, /my.txt. That means, "get a file named my.txt that is in the root directory of the classpath". I'm sure you can read more about getResource and getResourceAsStream to learn more about how to do this. But the key thing here is that the classpath for the file will be the same for any computer you give the executable to (as long as you don't move the file around in your classpath).
BTW, if you get a null pointer exception on the line that does new File, that means that you haven't specified the correct classpath for the file.

As far as I remember the default directory with be the same as your project folder level. Put the file one level higher.
-Project/
----src/
----test/
-Highscores.scr

If you are building your code on your eclipse then you need to put your Highscores.scr to your project folder. Try that and check.

You can try to run the following sample program to check which is the current directory your program is picking up.
File f = new File(".");
System.out.println("Current Directory is: " + f.getAbsolutePath());

Related

FileReader can not find file even though it is in working directory

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.

Error trying to read from a text file [duplicate]

I have a file named "word.txt".
It is in the same directory as my java file.
But when I try to access it in the following code this file not found error occurs:
Exception in thread "main" java.io.FileNotFoundException: word.txt
(The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.util.Scanner.<init>(Unknown Source)
at Hangman1.main(Hangman1.java:6)
Here's my code:
import java.io.File;
import java.util.*;
public class Hangman1 {
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(new File("word.txt"));
String in = "";
in = input.nextLine();
}
}
Put the word.txt directly as a child of the project root folder and a peer of src
Project_Root
src
word.txt
Disclaimer: I'd like to explain why this works for this particular case and why it may not work for others.
Why it works:
When you use File or any of the other FileXxx variants, you are looking for a file on the file system relative to the "working directory". The working directory, can be described as this:
When you run from the command line
C:\EclipseWorkspace\ProjectRoot\bin > java com.mypackage.Hangman1
the working directory is C:\EclipseWorkspace\ProjectRoot\bin. With your IDE (at least all the ones I've worked with), the working directory is the ProjectRoot. So when the file is in the ProjectRoot, then using just the file name as the relative path is valid, because it is at the root of the working directory.
Similarly, if this was your project structure ProjectRoot\src\word.txt, then the path "src/word.txt" would be valid.
Why it May not Work
For one, the working directory could always change. For instance, running the code from the command line like in the example above, the working directory is the bin. So in this case it will fail, as there is not bin\word.txt
Secondly, if you were to export this project into a jar, and the file was configured to be included in the jar, it would also fail, as the path will no longer be valid either.
That being said, you need to determine if the file is to be an embedded-resource (or just "resource" - terms which sometimes I'll use interchangeably). If so, then you will want to build the file into the classpath, and access it via an URL. First thing you would need to do (in this particular) case is make sure that the file get built into the classpath. With the file in the project root, you must configure the build to include the file. But if you put the file in the src or in some directory below, then the default build should put it into the class path.
You can access classpath resource in a number of ways. You can make use of the Class class, which has getResourceXxx method, from which you use to obtain classpath resources.
For example, if you changed your project structure to ProjectRoot\src\resources\word.txt, you could use this:
InputStream is = Hangman1.class.getResourceAsStream("/resources/word.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
getResourceAsStream returns an InputStream, but obtains an URL under the hood. Alternatively, you could get an URL if that's what you need. getResource() will return an URL
For Maven users, where the directory structure is like src/main/resources, the contents of the resources folder is put at the root of the classpath. So if you have a file in there, then you would only use getResourceAsStream("/thefile.txt")
Relative paths can be used, but they can be tricky. The best solution is to know where your files are being saved, that is, print the folder:
import java.io.File;
import java.util.*;
public class Hangman1 {
public static void main(String[] args) throws Exception {
File myFile = new File("word.txt");
System.out.println("Attempting to read from file in: "+myFile.getCanonicalPath());
Scanner input = new Scanner(myFile);
String in = "";
in = input.nextLine();
}
}
This code should print the folder where it is looking for. Place the file there and you'll be good to go.
Your file should directly be under the project folder, and not inside any other sub-folder.
If the folder of your project is named for e.g. AProject, it should be in the same place as your src folder.
Aproject
src
word.txt
Try to create a file using the code, so you will get to know the path of the file where the system create
File test=new File("check.txt");
if (test.createNewFile()) {
System.out.println("File created: " + test.getName());
}
I was reading path from a properties file and didn't mention there was a space in the end.
Make sure you don't have one.
Make sure when you create a txt file you don't type in the name "name.txt", just type in "name". If you type "name.txt" Eclipse will see it as "name.txt.txt". This solved it for me. Also save the file in the src folder, not the folder were the .java resides, one folder up.
I have the same problem, but you know why? because I didn't put .txt in the end of my File and so it was File not a textFile, you shoud do just two things:
Put your Text File in the Root Directory (e.x if you have a project called HelloWorld, just right-click on the HelloWorld file in the package Directory and create File
Save as that File with any name that you want but with a .txt in the end of that
I guess your problem is solved, but I write it to other peoples know that.
Thanks.
i think it always boils to the classpath. having said that if you run from the same folder where your .class is then change Scanner input = new Scanner(new File("word.txt")); to Scanner input = new Scanner(new File("./word.txt")); that should work

Why cant I change the the file extension of a desired file in java?

I cant understand why my code refuses to change the file extension of my txt file to java.
Here's my code:
public static void main(String[] arg) {
File file = new File("file.txt"); //File I want to change to .java
File file2 = new File("file.java");
boolean success = file.renameTo(file2); //boolean to check if successful
if (success == true)
{
System.out.println("file extension change successful");
}else
{
System.out.println("File extension change failed");
}
}// main
It always prints "file extension failed" each time and I honestly do not understand why. I'm starting to suspect it might be the permissions on my computer. The compiler I use is Eclipse.
FIXED:
THE CAUSE OF THE PROBLEM:
I had placed the file I wanted to change, file.txt, in the package folder inside my project folder. C:\Users\Acer\workspace\MyProjectName\src\MyPackageName. As a consequence the file could not be found by the system.
THE SOLUTION:
I simply moved the file, file.txt, into the main project folder; C:\Users\Acer\workspace\MyProjectName and this fixed the problem. When I run my program it returns
file extension change successful
.
Thank you all for your help. I really appreciate it.
The Source file i.e file.txt should exist in the mentioned path (in your case its should be inside the eclipse project folder) and no file with the destination file name i.e file.java should exist in the mentioned path.
After you execute your code it will give file extension change successful and file.txt will be gone, its content will be transferred to the file.java
The classic Java File API is pretty limited in a number of respects. In this case, you are getting no feedback as to why the move is failing.
My recommendation, if you are on Java 7, would be to switch to use the nio file functionality that was added in that version. Not only are you then making use of a newer, more robust API, but you should get better messaging as to why your copy is failing. Here is equivalent code to the code you posted.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class MoveFile {
public static void main(String[] arg) {
Path file = Paths.get("file.txt"); //File I want to change to .java
Path file2 = Paths.get("file.java");
try {
Files.move(file, file2);
System.out.println("file extension change successful");
} catch (IOException e) {
System.out.println("File extension change failed: " + e.getMessage());
e.printStackTrace();
}
}
}
For awareness, Oracle provides a good reference page for converting legacy file code to the nio code.

Where do I add a file to read from in Eclipse?

I have been trying to read a file into Eclipse. I've looked over other questions, but those answers did not remedy the situation (refreshing the project folder, using getProperty and specifying the correct path, etc.) I've moved the file into every folder and I get the same error. I've copied the file into the directory as shown here:
I've also pasted the code below. It's stupidly simple. The error I get is "FileInputStream.open(String) line: not available [native method]".
Any help would be appreciated. Code is below.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Modulo {
public static void main(String[] args) throws FileNotFoundException {
File questions = new File("input.txt");
Scanner sc = new Scanner(questions);
while(sc.hasNext()){
int x = sc.nextInt();
String divide = sc.next();
int y = sc.nextInt();
System.out.println(x % y);
}
}
}
The answer depends.
If you want the file to be embedded within your application when your deploy it (as a Jar file for example), then you can't use File to reference it, as you've tried to include it within your application.
Eclipse further complicates the matter, as you can't included resources within your src directory, but needs to be maintained within a resources directory at the same level as your src folder (this folder may need to be included as part of your build process, but I only have a passing knowledge of how Eclipse works)...
Once you've corrected for all this, you will then need to use Class#getResource to load the resource...for example...
try (InputStream is = Modulo.class.getResourceAsStream("/input.txt")) {
Scanner sc = new Scanner(is);
//...
} catch (IOException exp) {
exp.printStackTrace();
}
However, if you want the file to be an external resource to your program, then you need to place it within a location relative to the location that the program is executed.
Normally, I would suggest the project directory, but I have a funny feeling that Eclipse run's it's Java programs in a different location ... and I don't know if you can change it...
In this case, you could use System.out.println(new File(".").getAbsolutePath()); or System.out.println(new File(".").getCanonicalPath()); or System.out.println(System.getProperty("user.dir")); which will tell you where you program is currently running and place the file there.
Of course, once build (into a Jar) you would need to place the file within a context that was relative to the location it was executed from...
You copy that file into Project folder parallel to src. This is the place base path of your code.
Eclipse by default looks for the file in the main project directory in your case Remainders, if your file is not there, you get an exception. Try placing the file directly under your project and run the same program, it should run correctly.

java.io.IOException source exists but not in a directory

I am a real beginner at Java programming so I hope I'm not wasting anyone's time. I tried my best to research this but couldn't come up with a solution.
I am following the Lynda video series "Java Essential Training" and it's been very good so far. I am currently learning how to copy the contents of a text file onto a new text file. However, the video shows a alternative method by downloading commons IO from Apache commons and adding the .jar file to the project.
In the video the jar file was added to build path. My version of eclipse seemed to do it automatically as "Referenced Libraries" popped up, and when I tried to add it eclipse said it was already there.
I followed the video exactly. The code looks like this
package com.lynda.files;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
public class Main {
public static void main(String[] args) {
try {
File f1 = new File("loremipsum.txt");
File f2 = new File("target.txt");
FileUtils.copyDirectory(f1, f2);
System.out.println("File copied!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
When I ran the code I got the message in console
java.io.IOException: Source 'loremipsum.txt' exists but is not a directory
at org.apache.commons.io.FileUtils.copyDirectory(FileUtils.java:1371)
at org.apache.commons.io.FileUtils.copyDirectory(FileUtils.java:1261)
at org.apache.commons.io.FileUtils.copyDirectory(FileUtils.java:1230)
at com.lynda.files.Main.main(Main.java:16)
In the code it says the FileUtils imported but eclipse tells me "The source attachment does not contain the source for file FileUtils.class". I tried to change the attached source but it gave me the error "Could not write to file BlahBlahBlah.classpath (Access is denied)
Hopefully I didn't drone on about something obvious and simple. I thought it best to be as clear as possible in case someone else has a similar problem.
Edit
I feel so stupid. Thank you for your help. I clicked on "copyDirectory" instead of "copyFile". Next time, instead of panicking, googling every line of error and asking people for help, I'll take the time to go through each line and think about what it does. Thanks to all of you for your help and patience.
See (http://commons.apache.org/proper/commons-io/javadocs/api-2.4/org/apache/commons/io/FileUtils.html#copyFile%28java.io.File,%20java.io.File%29)
Use FileUtils.copyFile(f1, f2); instead of FileUtils.copyDirectory(f1, f2);
The source and target File parameters of copyDirectory must be directories, but you are suppling text files.
public static void copyDirectory(File srcDir,File destDir)
throws IOException
Copies a whole directory to a new location preserving the file dates.
This method copies the specified directory and all its child directories and files to the specified destination. The destination is the new location and name of the directory.
The destination directory is created if it does not exist. If the destination directory did exist, then this method merges the source with the destination, with the source taking precedence.
Note: This method tries to preserve the files' last modified date/times using File.setLastModified(long), however it is not guaranteed that those operations will succeed. If the modification operation fails, no indication is provided.
Parameters:
srcDir - an existing directory to copy, must not be null
destDir - the new directory, must not be null
Throws:
NullPointerException - if source or destination is null
IOException - if source or destination is invalid
IOException - if an IO error occurs during copying
Since:
1.1
(Source)
I found this that may be of help to you:
copyFile(File srcFile, File destFile) Copies a file to a new location preserving the file date.
static void copyFile(File srcFile, File destFile, boolean preserveFileDate) Copies a file to a new location.
static long copyFile(File input, OutputStream output) Copy bytes from a File to an OutputStream.
static void copyFileToDirectory(File srcFile, File destDir) Copies a file to a directory preserving the file date.
static void copyFileToDirectory(File srcFile, File destDir, boolean preserveFileDate) Copies a file to a directory optionally preserving the file date.
Source
Although it's from the Apache site, it does talk about the Java classes.
Please read the error message again:
Source 'loremipsum.txt' exists but is not a directory
This is not exactly what you wrote in your subject. Indeed the file 'loremipsum.txt' exists but it not a directory. It is regular file. However you try to call FileUtils.copyDirectory() and pass this regular file to this method. But this method is not ready to work with files. It supports directories only. This is exactly what is written in error message.
EDIT
Now the question is why do you call method that definitely for intended for directories with parameters that are definitely files?

Categories