Error in Java with file reading - java

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.

Related

File (.txt) cannot be found

I am creating a stock market simulator (beginner) and I made a .txt file to save the stock symbol and name within a file. I am having an issue where my code is unable to find the file on my desktop.
public static void load() throws FileNotFoundException {
File file = new File("/Users/dhruvchaudhari/Desktop/stocks.txt");
Scanner scan = new Scanner(file);
while ((scan.hasNextLine())) {
System.out.println(scan.nextLine());
}
}
The error it is throwing is as such
java.io.FileNotFoundException: /Users/*username*/Desktop/stocks.txt (No such file or directory)
I'm on Mac and I checked the directory for the file directory and it should be correct. Any suggestions?
You can check the current working directory to confirm the path of your file by adding System.out.println("Working Directory = " + System.getProperty("user.dir"));
this will return the path you can debug this to get the idea of path in your application.
Also you can add read the file if its not there the code will create it for so you can add your metadata into the generated file.
By using this approach I hope you can move ahead.
public static void load() throws IOException {
File yourFile = new File(path);
yourFile.createNewFile(); // if file already exists will do nothing
Scanner scan = new Scanner(yourFile);
while ((scan.hasNextLine())) {
System.out.println(scan.nextLine());
}
}
Obviously your path is wrong or the file doesn't exist. You can use the if statement to determine whether the file exists first, and create the file when it does not exist.

Java: No Such File Or Directory (Using Scanner Class)

I'm trying to read from a file using the Scanner and File class:
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class TextFileReaderV1
{
public static void main(String[] args) throws IOException
{
String token = "";
File fileName = new File("data1.txt");
Scanner inFile = new Scanner(fileName);
while( inFile.hasNext() )
{
token = inFile.next( );
System.out.println(token);
}
inFile.close();
}
}
However, it is saying, "no such file or directory". and giving me the "java.io.FileNotFoundException"
I am using IntelliJ IDEA and the file is in the current directory I am working in: src/data1.txt -> next to GetFile.java (current code)
Full Error Message:
Exception in thread "main" java.io.FileNotFoundException: data1.txt (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.util.Scanner.<init>(Scanner.java:611)
at GetFile.main(GetFile.java:19)
**Edit: ** It has been solved!! The run configuration was set to the project directory, not the src one, so I implicitly added it in the argument:
File fileName = new File("src/data1.txt");
The run configuration was set to the project directory, not the src one, so I implicitly added it in the argument:
File fileName = new File("src/data1.txt");
Try entering the full path of the file. If that works, you can either be done at that point or look into relative file paths.

File Not Found w/ FileInputStream

I'm trying check and see if my program is scanning in the contents of a File however get this error:
Exception in thread "main" java.io.FileNotFoundException: input.txt (The system cannot find the file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at lottery.main(lottery.java:40)
I don't see the problem as in my code as I always do my files this way, can't seem to understand to the problem.
Code:
public static void main(String[] args) throws FileNotFoundException
{
Scanner in = new Scanner(System.in);
System.out.println("Enter the name of the file with the ticket data.");
String input = in.nextLine();
File file = new File(input);
in.close();
Scanner scan = new Scanner(new FileInputStream(file));
int lim = scan.nextInt();
for(int i = 0; i < lim * 2; i++)
{
String name = scan.nextLine();
String num = scan.nextLine();
System.out.println("Name " + name);
}
scan.close();
}
A FileInputStream obtains input bytes from a file in a file system. What files are available depends on the host environment. From docs.oracle.com
This means your FileInputStream wants an actual file system file provided. But you only made a filehandler when calling new File(). so you need to create the file on the file system calling file.createNewFile();
File file = new File(input); //here you make a filehandler - not a filesystem file.
if(!file.exists()) {
file.createNewFile(); // create your file on the file system
}
Scanner scan = new Scanner(new FileInputStream(file)); // read from file system.
Check if you start the jvm from the directory where the input file is located.
If not there is not possibility to find it with a relative path. Eventually change it to an absolute path (something like /usr/me/input.txt).
If the file is located on the directory where you start the java program check for the rights of the file. It could be not visible for the user launching the java program.
The problem is that your program could not find input.txt in the current working directory.
Look in the directory where is your program running and check it has a file called input.txt in it.

File Not Found after throws IOException

I get this exception when I try to read from a file:
ERROR:
Exception in thread "main" java.io.FileNotFoundException: newfile.txt (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.util.Scanner.<init>(Scanner.java:611)
at Postal.main(Postal.java:19)
import java.util.Scanner;
import java.io.*;
public class Postal {
public static void main(String[] args) throws Exception {
/*** Local Variables ***/
String line;
Scanner filescan;
File file = new File("newfile.txt");
filescan = new Scanner(file);
userInfo book = new userInfo();
/*** Loop through newfile.txt ***/
while (filescan.hasNext()) {
line = filescan.nextLine();
book.addNew(line);
}
book.print(0);
}
}
The class Scanner uses a FileInputStream to read the content of the file.
But it can't find the file so a exception is thrown.
You are using a relative path to the file, try out an absolute one.
Use this instead:
File file = new File(getClass().getResource("newfile.txt"));
Provide an absolute path the location where you want to create the file. And check that user has rights to create file there. One way to find the path is:
File f = new File("NewFile.txt");
if (!f.exists()) {
throw new FileNotFoundException("Failed to find file: " +
f.getAbsolutePath());
}
Try this to open file:
File f = new File("/path-to-file/NewFile.txt");

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

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.

Categories