Scanner Class couldnt find the file
I use NetBeansIDE, and the test.txt is in the folder path: D:\netbeans project works\ReadFile\src\readfile\test.txt
in the same folder the readfile.java exsist.
the code is as below.
It generates file not found.
package readfile;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) throws IOException , FileNotFoundException
{
Scanner scanner = new Scanner(new File("test.txt"));
while (scanner.hasNextLine())
System.out.println(scanner.nextLine());
}
}
output:-
run:
Exception in thread "main" java.io.FileNotFoundException: test.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:106)
at java.util.Scanner.<init>(Scanner.java:636)
at readfile.ReadFile.main(ReadFile.java:14)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
Add the following before creating Scanner class:
System.out.println(new File("test.txt").getAbsolutePath());
It will show you where JVM expects to find the file and whether it is the folder you expect as well.
Also check file permissions. But most likely it is a problem with default JVM directory.
Ahhh you aren't specifying the full file path. When a file path is abbreviated (i.e. test.txt), java assumes that the file is in the same directory as the source code that is running it. So either specify the full path, or move the file.
Move it to the ReadFile directory, i.e. the root of the project
The test.txt file should be in the folder where the file readfile.class exists.
I am aware that this problem has been reported a long time ago, however, I have faced a similar obstacle and then the proposed solutions didn't work, thus I decided to post another answer.
Try using try... catch clause. For instance, only then my code has become compiled by NetBeans.
what worked for me was removing .txt extension from the file name and using . to specify current directory (example shown below).
Scanner scanner = new Scanner(new File("./test"));
Related
I'm new to IntelliJ. I'm running into problems on running very basic File I/O programs.
import java.io.*;
import java.util.Scanner;
public class NamePlaces {
public static void main(String[] args) throws FileNotFoundException{
String nameTxt = args[0];
String placeTxt = args[1];
Scanner nameScanner = null;
Scanner placeScanner = null;
try{
FileReader names = new FileReader(nameTxt);
FileReader places = new FileReader(placeTxt);
nameScanner = new Scanner(new BufferedReader(names));
placeScanner = new Scanner(new BufferedReader(places));
while(nameScanner.hasNext() && placeScanner.hasNext()){
System.out.format("%s lives in %s \n",nameScanner.next(),placeScanner.next());
}
}finally {
if (nameScanner != null){
nameScanner.close();
}
if (placeScanner != null){
placeScanner.close();
}
}
}
here's my project structure
and here's my output
/usr/lib64/jvm/java/bin/java -javaagent:/home/abhishek/intellij/lib/idea_rt.jar=42185:/home/abhishek/intellij/bin -Dfile.encoding=UTF-8 -classpath /home/abhishek/Documents/code/ideaprojects/files/out/production/files NamePlaces names.txt places.txt
Exception in thread "main" java.io.FileNotFoundException: names.txt (No such file or directory)
at java.base/java.io.FileInputStream.open(FileInputStream.java:219)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:157)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:112)
at java.base/java.io.FileReader.<init>(FileReader.java:60)
at NamePlaces.main(NamePlaces.java:12)
Process finished with exit code 1
So I've been wrestling with this problem for quite some time now. I do not understand why it won't read the file names.txt when it is available in the src folder as well as the out/production/files folder too. What am I missing. I've tried changing directories, classpath seems right too. I'm out of options here. Any help is appreciated. thanks.
In Java if you are not using class.getResource() it will be looking in the project/surrounding folder. If you compiled the .class file by hand it would work in its current state. But to fix the issue moving names.txt and places.txt to the files project folder will fix it.
I am able to run the program. I however could not figure out a simpler way than this.
So I changed my code by adding
import java.nio.file.Path;
import java.nio.file.Paths;
to the imports.
And inside the main(), I added the following statement to get the path.
Path path = Paths.get('path/to/directory/');
And then I used this path to hard code the path into the call to the FileReader such as
FileReader names = new FileReader(path.toString()+"/"+namesTxt);
This got the program running. I know this is not the optimum or the desired solution but at the moment, I wanted the program to run.
I will update the answer once I learn more about how the IntelliJ works in identifying files because hard coding paths is not a good software design practice.
package files;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.File;
public class file {
public static void main(String[] args)throws FileNotFoundException {
File file = new File("txtfile.txt");
Scanner input = new Scanner(file);
while (input.hasNextLine()) {
System.out.println(input.nextLine());
}
}
}
Where it says file.txt I have to enter the full file path. All tutorials I watch do not have to do this.
Yeah! File file = new File("txtfile.txt"); txtfile.txt is a path to your file that you want to read. Provide the path where file is like "C:\Users\me\Desktop\txtfile.txt" if the file is not in the same directory where your java file is. After you compile the java file a .class file is created it that .class file is also created in the same folder it will work with.
File file = new File("txtfile.txt"); and you don't need to specify the full path.
If not you then you have to provide the absolute file path like above.
If you don't enter the path it won't compile and show error.
To set a path..
Open the command prompt and it show something like this
C:user>admin
You need to change it and point it your program saved location (use cd for change it)
Then type path="
And go to localdisc C: and open programfile->java->jdk->bin
Then save the path at above
Which is something like c:/programfile/java/jdk1. 0./bin
Save and copy it in front of path="c:/programfile/java/jdk1. 0./bin";
Then press enter
Then compile the program using javac filename. Java
And run using java filename
I've got a text frequency analysis program, I'm trying to alter this program so that it'll read all the text in a text file you specify. Every time I input the file name it throws an error at me, any idea where I'm going wrong?
Error Message:
Exception in thread "main" java.io.FileNotFoundException: file.txt (No
such file or directory) at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.(FileInputStream.java:120) at
java.util.Scanner.(Scanner.java:636) at
Charnock_John_4_.main(Charnock_John_4_.java:11) –
Code:
import java.util.*;
import java.io.*;
public class J_<countlettersfilereader> {
public static void main(String[] args)throws Exception {
// open the file
Scanner console = new Scanner(System.in);
System.out.print("What is the name of the text file? ");
String fileName = console.nextLine();
Scanner input = new Scanner(new File(fileName));
//
How to deal with the FileNotFoundException
If the message of the exception claims that there is no such file or
directory, then you must verify that the specified is correct and
actually points to a file or directory that exists in your system.
If the message of the exception claims that permission is denied then, you must first check if the permissions of the file are correct
and second, if the file is currently being used by another
application.
If the message of the exception claims that the specified file is a
directory, then you must either alter the name of the file or delete
the existing directory (if the directory is not being used by an
application).
Important:
For those developers that use an IDE to implement their Java
applications, the relative path for every file must be specified
starting from the level where the src directory of the project
resides.
Note: Your issue is number option one.
What I do to resolve this issue?
I usually use absolute path which I do not recommend because it is just Micky Mouse job.
Use relative path because your program will be path independent.
I am trying to read a file in Java. I wrote a program and saved the file in the exact same folder as my program. Yet, I keep getting a FileNotFoundException. Here is the code:
public static void main(String[] args) throws IOException {
Hashtable<String, Integer> ht = new Hashtable<String, Integer>();
File f = new File("file.txt");
ArrayList<String> al = readFile(f, ht);
}
public static ArrayList<String> readFile(File f, Hashtable<String, Integer> ht) throws IOException{
ArrayList<String> al = new ArrayList<String>();
BufferedReader br = new BufferedReader(new FileReader(f));
String line = "";
int ctr = 0;
}
...
return al;
}
Here is the stack trace:
Exception in thread "main" java.io.FileNotFoundException: file.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
at csfhomework3.ScramAssembler.readFile(ScramAssembler.java:26)
at csfhomework3.ScramAssembler.main(ScramAssembler.java:17)
I don't understand how the file can't be found if it's in the exact same folder as the program. I'm running the program in eclipse and I checked my run configurations for any stray arguments and there are none. Does anyone see what's wrong?
Because the File isn't where you think it is. Print the path that your program is attempting to read.
File f = new File("file.txt");
try {
System.out.println(f.getCanonicalPath());
} catch (IOException e) {
e.printStackTrace();
}
Per the File.getCanonicalPath() javadoc, A canonical pathname is both absolute and unique. The precise definition of canonical form is system-dependent.
Check the Eclipse run configuration. Look on the second tab "Arguments", at the bottom pane where it says "Working Directory". That's the place where the program gets launched and where it will expect to find the file. Usually in Eclipse it launches your program with the current working directory set to be the base project directory. If you have the java class file in a source folder and are using proper package (e.g., "com.mycompany.package"), then the data file will be in a directory like "src/com/mycompany/package" which is quite a different directory from the project directory.
HTH
File needs to be in the class path and not in the source path. Copy the file in output/class files folder and it should be available.
You should probably check out this question: Java can't find file when running through Eclipse
Basically you need to be sure where the execution is taking place (current directory) and how your SO will resolve the relative paths. Try changing the working directory in Eclipse' Run Configurations>Arguments or provide the absolute filename
I'm extremely late to responding to this question, but I see that this is still an extremely hot topic to this day. It may not seem obvious, but what you want to use here is actually the newer file-handling i/o library, java.nio. The below explained example shows how to read a String from a file path, but I encourage you to take a look at the docs if you have a different use.
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Files;
public static void main(String[] args) throws IOException {
Path path = Path.of("app/src/main/java/pkgname/file.txt");
String content = Files.readString(path);
System.out.println(content); // Prints file content
}
Okay, code done, now time for the explanation. I'll start off with the import statements. java.io.IOException is necessary for some exception-handling. (Sidenote: Do not omit the throws IOException and/or the IOException import. Otherwise Files.readString() may throw an error in your editor, which I'll get to shortly). The Path class import is necessary to actually get the file, and the Files class import is necessary for file operations.
Now, the main function itself. The first line receives a Path object representing a file for you to actually read/write. Here the question of path name arises, which is the basis of the question. I have seen other solutions that tell you to take the absolute path of your file, but don't do that! It's extremely bad practice, especially with open-source or public code. Path.of actually allows you to use the path relative to your root folder (unless it isn't in a directory, simply inputting the file name does not work, I'm afraid). The example path name I gave is an example of a Gradle project. Next line, we get the content of the file as a String using a method from Files. Again, if you have a different use for a file, you can check the docs (a different method from the Files class will probably work for you). On the final line, we print the result. Hooray! Our output is just what we needed.
There you have it, using Path instead of File is the solution to this annoying bug. Hopefully this helps!
Trying to learn how to read text files in Java. I have placed the text file within the same folder as IdealWeight.java. Am I missing something here?
IdealWeight.java
package idealweight;
import java.util.*;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class IdealWeight
{
public static void main(String[] args)
{
Scanner fileIn = null; //Initializes fileIn to empty
try
{
fileIn = new Scanner
(
new FileInputStream
("Weights.txt")
);
}
catch (FileNotFoundException e)
{
System.out.println("File not found!");
}
}
}
You could also put the file in the classpath and then do this:
InputStream in = this.getClass().getClassLoader()
.getResourceAsStream("Weights.txt");
Just another idea.
The java file IO system does not look for the file in the same directory as the class, but in the "default" directory for the application. Any application you run has a directory that it regards as its default, and that's where it would attempt to open this file. Try putting a full pathname to the file.
Or put the file you want to read in a directory, and run the application from that directory (in a terminal window) with "java IdealWeight".
You need to put Weights.txt in your working directory, not in the directory with the source file. If you're using Eclipse or a similar IDE, the this is probably the project root. As per this answer, you can use this snippet to get the full path to your working directory:
System.out.println("Working Directory = " + System.getProperty("user.dir"));
Check the result of running that command, and that should tell you where to put your text file. Once you have the text file in the right place then the code you posted should work fine.