I am trying to use Java.util.scanner on a txt to parse it. I am having trouble trying to scan the file because the file isn't found.
My class is within the same package of the txt file. So can you please tell me how to scan a file within the same package of the class.
public class PhoneBook {
private ArrayList<PhoneBookEntry>[] buckets;
public void load() {
try {
Scanner scan = new Scanner(new File("phone.txt"));
} catch (FileNotFoundException e) {
System.out.println("File Not Found");
}
}
public static void main(String[]args) {
PhoneBook phone = new PhoneBook();
phone.load();
}
}
Here is the StackTrace of the error
java.io.FileNotFoundException: phone.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 HashSet.PhoneBook.load(PhoneBook.java:13)
at HashSet.PhoneBook.main(PhoneBook.java:23)
Put the file in the root of your class path (after compilation, your file should appear in the root folder where .class files are generated) and use the code syntax below:
InputStream is = getClass().getClassLoader().getResourceAsStream("phone.txt");
Scanner fileScanner = new Scanner(is);
new File("phone.txt")
looks up the file in the current working directory. This is the directory where you started the java virtual machine.
You say that it is located in the same package as the class, which is most likely a different directory (e.g. src/com/mypackage).
Try moving the file to the root directory of your project. You should then be able to load it.
A different approach is shown in the answer from #Yogendra, which should work also when the file is located in the same package binary directory as your .class file. But I am not sure if you want to load this kind of file as a resource.
As stated in one of the comments, you need to put the file where the .jar is generated. If you're running from Netbeans/Eclipse, this will be the root folder of your project, if you're running from the compiled .jar, it will be the same directory as the .jar. Packages are only folders used to organise and separate source files.
But if you want to have the file in the same package anyway, you can always do something like (presuming you only have one package):
new File("./src/myPackage/myFile.txt")
Related
Code:
import java.io.*;
import java.util.Scanner;
public class Driver {
private int colorStrength;
private String color;
public static void main(String[] args) throws IOException {
String line, file = "strength.txt";
File openFile = new File(file);
Scanner inFile = new Scanner(openFile);
while (inFile.hasNext()) {
line = inFile.nextLine();
System.out.println(line);
}
inFile.close();
}
}
This is a small part of a program I am writing for a class (the two private attributes have yet to be used I know) but when I try to run this with the strength.txt file I receive the following errors:
Exception:
Exception in thread "main" java.io.FileNotFoundException: strength.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 Driver.main(Driver.java:14)
If anyone with Eclipse could help me figure this out it would be much appreciated!
You've used a relative file path which is relative to your project execution.
If you'd like to do it that way, simply put the strength.txt file in the base directory of your project. Like so:
Alternatively, you could reference the absolute file path on your system. For example, use:
Windows:
C:/dev/myproject/strength.txt
Mac/Unix:
/Users/username/dev/strength.txt
(or whatever the full path may be) instead.
Do this
System.out.println(openFile.getAbsolutePath());
It will show you where JVM expects to find the file and whether it is the folder you expect as well, Accordingly place the file or give the exact location
Use this to see what file path the system is using to reach the relative path
System.out.print(System.getProperty("user.dir"));
Then make sure that the relative path immediately follows this path.
You can also turn that into a string by doing
String filePath = System.getProperty("user.dir");
and then you can just add that to the beginning of the filepath like so,
ImageIcon imageIconRefVar = new ImageIcon(filePath + "/imagepathname");
I found this solved the issue for me when I used it in the path (which seemed odd since that should be the location it is in, but it worked)
You've used a relative file path which is relative to your project execution.
If this works for you, you can change the execution directory from the project root to the binary directory by:
"Run" -> "Run configurations"
In the "Arguments" tab, find "working directory" settings.
Switch from "Default" to "Other".
Click the "Workspace" button and select the project in pop-up window then click "OK"; this will bring you something like $(workspace_loc:proj-1).
Append "/bin" to the end of it; save the configuration.
I need this instead of simply putting files in project root directory when I am doing assignment and the professor requires specific file hierarchy; in addition, this is more portable than absolute path.
Inside the base directory create a folder, name it "res". Place your file inside "res" folder.
use String file = ".\\res\\strength.txt"; to reference the location of your file.
You should use a resource folder to store all the files you use in your program (a good practice).
And make a refrence of that file from your root directory. So the file is present within the package.
When creating a PrinterWriter object:
PrintWriter outputFile = new PrintWriter(*FileName*);
Where is the compiler looking when it goes to find FileName? For example, in Eclipse I am working in Arrays/src/ArraysAndFiles.java. In this example I am trying to open Values.txt. I have created this file in the src directory since that is where ArraysAndFiles.java is stored. When I attempt to open the file in the following code I get a FileNotFoundException:
import java.io.PrintWriter;
public class ArraysAndFiles {
public static void main(String[] args) {
// TODO Auto-generated method stub
PrintWriter outputFile = new PrintWriter("Values.txt");
}
}
What is the proper path to Values.txt?
Solution #1 (recommended for small files but you have the benefit that file will be found in other computers as well): How do I load a file from resource folder?
Solution #2: Build the path step by step by using File(String parent, String child) constructor. Example:
File desktop = new File(System.getProperty("user.home"),"Desktop");
File textsFolder = new File(desktop,"texts");
File testsFolder = new File(textsFolder,"tests");
File peopleTxt = new File(testsFolder,"people,txt");
Which is equals to: C://Users//George//Desktop//texts//tests//people.txt (Windows OS).
As per code,
PrintWriter outputFile = new PrintWriter("Values.txt");
if you place your Values.txt in current/project directory i.e. in Arrays folder it should work but there are limitation as mentioned in above comments like writing to the file which is a part of JarFile.
Depending upon your purpose, you should take the action.
In your example "Values.txt" is a relative path. It's relative to your working directory.
Usually it's the same directory where your JAR file resides.
In Eclipse an application is built in the 'bin' folder. In your case it's Arrays\bin\. So this is the working directory for the application and your file has to be there.
If you want Eclipse to export this file during the Build process, do the following:
Right click on the file -> Build Path -> Add to Build Path
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
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.
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].