java.io.FileNotFoundException: in.txt, (The system cannot find the file specified) - java

I'm getting the following error
java.io.FileNotFoundException: in.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.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
at FileTest.main(FileTest.java:50)
Yet Im certain that I have created a in.txt file under the src, bin, and root directory. I also tried specifying the full directory in my main parameters, but still not working. Why isn't Eclipse picking it up?
import java.io.*;
public class FileTest {
public static void main(String[] args) {
try {
String inFileName = args[0];
String outFileName = args[1];
BufferedReader ins = new BufferedReader(new FileReader(inFileName));
BufferedReader con = new BufferedReader(new InputStreamReader(System.in));
PrintWriter outs = new PrintWriter(new FileWriter(outFileName));
String first = ins.readLine(); // read from file
while (first != null) {
System.out.print("Type in a word to follow " + first + ":");
String second = con.readLine(); // read from console
// append and write
outs.println(first + ", " + second);
first = ins.readLine(); // read from file
}
ins.close();
outs.close();
} catch (IOException ex) {
ex.printStackTrace(System.err);
System.exit(1);
}
}
}

Given the error message, I would guess that Java is looking for the file name in.txt,, with a trailing comma.

I took your code and executed it with the following command-line params:
in.txt out.txt
It works with no problems at all. Check your command line.

By default, Eclipse will set the working directory to the project folder. If you have made changes to the settings, you can still find out the working directory by this simple line of code:
System.out.println(new java.io.File("").getAbsolutePath());
Put your text file in the folder printed, and you should be fine.

Put it in the project directory and if that doesn't work, the bin folder

Open your "Debug Configurations" and set, under the tab "Arguments", the Working Directory. Relative paths will be relative to the Working directory.

I created a new project Learning in my eclipse and put in.txt file inside a source directory . I tested using the sample java file .
public static void main(String[] args) {
File f = new File("a.txt");
System.out.println(f.getAbsolutePath());
}
Output:
/home/bharathi/workspace/Learning/a.txt
It looks in a project root directory . You can put in.txt inside a project's root directory or give the path until source directory .

There can be two problems:
In your console, the error shown with the ',' check -- >
java.io.FileNotFoundException: in.txt,
so probably JVM looks for a filename with the ','
The second case can be, You in.txt file is not in the right
location. Check whether it's is the Root of the project. or the main
path.
That would solve these types of problems.

Related

Why can't I find my File?

I'm trying to open a CSV file name "logger.csv" which I have saved in the source folder itself.
public static void main(String[] args) {
String filename = "logger.csv";
File motor_readings = new File(filename);
try {
Scanner inputStream = new Scanner(motor_readings);
while (inputStream.hasNext()){
System.out.println(inputStream.next());
}
inputStream.close();
} catch (FileNotFoundException e) {
System.out.println("Error: File not found!");
}
}
However, this keeps on giving me a "File not found" error.
If you use relative pathing as you are right now - the file needs to exist in the project root, not in the directory of the java file.
Consider this hierarchy:
project/
src/main/java
file.java
logger.csv
new File("logger.csv") will not work.
project/
logger.csv
src/main/java
file.java
new File("logger.csv") will now work. (notice, the file is adjacent to the src directory.)
Put the file on level up. In the main folder of the project.
To see where the file is expected update the code in your catch clause to:
System.out.println("Error: File not found: " + motor_readings.getAbsolutePath());
Put it there and be sure to refresh your workspace in Eclipse so that the file can be seen.

Program not reading txt file

I am a beginner Java student, working on our first class assignment.
In this assignment, I need to read a txt file, and fill an array with its contents, first space in the array per line.
My professor gave us code to do this, but I keep getting an error that the file cannot be read each time I try.
I am using Netbeans 8, on a Mac, and the file States.Fall2014.txt is located in the src folder, with all of my java classes.
Exception in thread "main" java.io.FileNotFoundException: States.Fall2014.txt (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at java.io.FileReader.<init>(FileReader.java:58)
at main.main(main.java:21)
Java Result: 1
Here is the code I have. I have only included the code that pertains to opening the file, as I'm sure you have no wish to be spammed with the other classes.
The commented code during the trimming is to echo print, to make sure the file is being read in properly (not currently needed since the file isn't being read in at all).
import java.io.*;
public class main {
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
public static void main(String args[]) throws IOException {
StateCollection Sdriver = new StateCollection(50);
//Sdriver = new StateCollection(50);
//Creates object of collection class
FileReader fr= new FileReader("States.Fall2014.txt");
BufferedReader br1 = new BufferedReader (fr);
String inputString;
String stateName;
String stateCapital;
String stateAbbrev;
int statePop;
String stateRegion;
int stateRegionNum;
inputString = br1.readLine();
while (inputString != null)
{
stateName = inputString.substring(1, 15).trim();
//System.out.println("stateName read in was: " + stateName);
stateCapital = inputString.substring(16, 30).trim();
//System.out.println(“stateCapital read in was: “ + stateCapital);
stateAbbrev = inputString.substring(31, 32).trim();
//System.out.println(“stateAbbrev read in was: “ + stateAbbrev);
statePop = Integer.parseInt(inputString.substring(33, 40));
//System.out.println(“statePop read in was: “ + statePop);
stateRegion = inputString.substring(41, 55).trim();
//System.out.println(“stateRegion read in was: “ + stateRegion);
stateRegionNum = Integer.parseInt(inputString.substring(56));
//System.out.println(“stateRegionNum read in was: “ + stateRegionNum);
//Code to create object
inputString = br1.readLine(); // read next input line.
}
br1.close(); //Close input file being read
Change
FileReader fr= new FileReader("States.Fall2014.txt");
to
FileReader fr= new FileReader("src/States.Fall2014.txt");
or move the file up one level to the project directory.
Make sure that the TXT file is in the right folder/area.
You shouldn't have it with your class, as the other answer states, you need it in the root folder.
Move the file up one level, to the same as the src folder.
The src directory is not (necessarily) the directory the .class file is in. Make sure States.Fall2014.txt is on the class-path.

Error in Java with file reading

So there is the code:
public class Main{
public static void main(String[] argv) throws IOException{
new Main().run();
}
PrintWriter pw;
Scanner sc;
public void run() throws IOException{
sc = new Scanner(new File("input.txt"));
int a=sc.nextInt();
pw = new PrintWriter(new File("output.txt"));
pw.print(a*a);
pw.close();
}
}
Error:
Exception in thread "main" java.io.FileNotFoundException: input.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 Main.run(Main.java:14)
at Main.main(Main.java:8)
Like i understand it can't find file named input.txt, BUT! I have that file in same directory where Main class is, what can be the promblem then?
p.s Tried on cmd and eclipse, both give same error.
it is not relative to your Main class, it is relative from where you launch this Java program (i.e. current work directory)
it is relative to
System.getProperty("user.dir")
You probably need to specify the PATH to your file, one thing you can do is test for existence and readability with File.canRead() like
File file = new File("input.txt");
if (!file.canRead()) {
System.err.println(file.getCanonicalPath() + ": cannot be read");
return;
}
An example using a PATH might be (for Windows) -
File file = new File("c:/mydir/input.txt");
You can use System.out.println(System.getProperty("user.dir")) to see where Java is looking for the file by default. This is most likely your project folder. This is were you have to put the file if you don't want to specify an absolute path.

program is unable to find the file

i am trying to run a simple java program that reads from a file:
public static void main(String[] args)
throws FileNotFoundException {
Scanner input = new Scanner(new File("weather.txt"));
double prev = input.nextDouble(); // fencepost
for (int i = 1; i <= 7; i++) {
double next = input.nextDouble();
System.out.println(prev + " to " + next +
", change = " + (next - prev));
prev = next;
}
}
}
but i keep getting the following input:
Exception in thread "main" java.io.FileNotFoundException: weather.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 Files.test.main(test.java:9)
the file weather.txt is in the same folder as the .java program, and i am using eclipse kepler.
the file weather.txt is in the same folder as the .java program, and i
am using eclipse kepler.
src directory is for .java files. You should place weather.txt on project directory of Eclipse Kepler workspace.
If you put this line
System.out.println("current dir : " + System.getProperty("user.dir"));
just to see where the program is reading files from. You may then need to set the directory you are reading from relative to the class that is being run eg,
URL url = getClass().getResource("weather.txt");
File file = new File(url.toURI());
Eclipse Run Configuration allows you to set the directory where your program is running. Either set the directory accordingly, or use a path relative to the directory where you are running. This is usually the workspace directory.

Java, reading a file from current directory?

I want a java program that reads a user specified filename from the current directory (the same directory where the .class file is run).
In other words, if the user specifies the file name to be "myFile.txt", and that file is already in the current directory:
reader = new BufferedReader(new FileReader("myFile.txt"));
does not work. Why?
I'm running it in windows.
Try
System.getProperty("user.dir")
It returns the current working directory.
The current directory is not (necessarily) the directory the .class file is in. It's working directory of the process. (ie: the directory you were in when you started the JVM)
You can load files from the same directory* as the .class file with getResourceAsStream(). That'll give you an InputStream which you can convert to a Reader with InputStreamReader.
*Note that this "directory" may actually be a jar file, depending on where the class was loaded from.
None of the above answer works for me. Here is what works for me.
Let's say your class name is Foo.java, to access to the myFile.txt in the same folder as Foo.java, use this code:
URL path = Foo.class.getResource("myFile.txt");
File f = new File(path.getFile());
reader = new BufferedReader(new FileReader(f));
Files in your project are available to you relative to your src folder. if you know which package or folder myfile.txt will be in, say it is in
----src
--------package1
------------myfile.txt
------------Prog.java
you can specify its path as "src/package1/myfile.txt" from Prog.java
If you know your file will live where your classes are, that directory will be on your classpath. In that case, you can be sure that this solution will solve your problem:
URL path = ClassLoader.getSystemResource("myFile.txt");
if(path==null) {
//The file was not found, insert error handling here
}
File f = new File(path.toURI());
reader = new BufferedReader(new FileReader(f));
Thanks #Laurence Gonsalves your answer helped me a lot.
your current directory will working directory of proccess so you have to give full path start from your src directory like mentioned below:
public class Run {
public static void main(String[] args) {
File inputFile = new File("./src/main/java/input.txt");
try {
Scanner reader = new Scanner(inputFile);
while (reader.hasNextLine()) {
String data = reader.nextLine();
System.out.println(data);
}
reader.close();
} catch (FileNotFoundException e) {
System.out.println("scanner error");
e.printStackTrace();
}
}
}
While my input.txt file is in same directory.
Try this:
BufferedReader br = new BufferedReader(new FileReader("java_module_name/src/file_name.txt"));
try using "."
E.g.
File currentDirectory = new File(".");
This worked for me

Categories