File Not Found w/ FileInputStream - java

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.

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.

Failing to read text file content java

I am working on a java console application, which is supposed to have login interface for admin and normal user, reading and verifying the input against contents of a text file.
I however seem to be stuck at reading the contents of the text file, and it continually gives an error that states: "Failed to locate file"
Below is my code that locates and read the content of the text file.
//Method for teller/shop assistant login
public static void tellerLogin(){
//loading and reading the text file containing the login credentials
Scanner scan = new Scanner (new File("the \\ dir\\myFile.extension"));
Scanner keyboard = new Scanner (System.in);
String user = scan.nextLine();
String pass = scan.nextLine();
//String variables to hold the data retrieved from the text file
String inpUser = keyboard.nextLine();
String inPass = keyboard.nextLine();
//Verifying the user input against the text file contents for verification
if (inpUser.equals(user) && inPass.equals(pass)){
System.out.println(" Logged in as Admin");
tellerMenu();
}
else{
System.out.println("Incorrect credentials");
}
}
Here is the error:
SEVERE: null java.io.FileNotFoundException: D:\pasd\adminlogin.txt (The system cannot find the file specified) 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
kiosk.Kiosk.adminLogin(Kiosk.java:89) at kiosk.Kiosk.main(Kiosk.java:35)
if you want to use an absolute Path file in here, then you need
new File("the \ dir\myFile.extension");
the \ dir\myFile.extension is the absolute Path;
Note example syntax for:
windows system:C:\1.txt,
Mac or linux:/Users/home/xxx.txt
if you set your file as a relative path, your resource file in your resources directory can be used: YouClass.class.getClassLoader().getResource(path)
E.g.
String path="1.txt";//set your file path
//get file resource
URL resource = MainTest.class.getClassLoader().getResource(path);
//if file not exist
if(resource==null){
throw new NullPointerException("not found a resource file")
}
//create file using path
File file= new File(resource.getFile());
//get file
Scanner scan = new Scanner (file);
Specifically, for your problem:
you need confirm your file in path D:\pasd\adminlogin.txt,
you can change your path separator \ to / for D:/pasd/adminlogin.txt;
suggest you put your adminlogin.txt in you project resources directory
this project is ab example for your problem :
https://github.com/lonecloud/stackoverflow/

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.

Getting FileNotFoundException even though file exists and is spelled correctly [duplicate]

This question already has answers here:
Java says FileNotFoundException but file exists
(12 answers)
Closed 3 years ago.
I'm creating a small program that will read a text file, which contains a lot of randomly generated numbers, and produce statistics such as mean, median, and mode. I have created the text file and made sure the name is exactly the same when declared as a new file.
Yes, the file is in the same folder as the class files.
public class GradeStats {
public static void main(String[] args){
ListCreator lc = new ListCreator(); //create ListCreator object
lc.getGrades(); //start the grade listing process
try{
File gradeList = new File("C:/Users/Casi/IdeaProjects/GradeStats/GradeList");
FileReader fr = new FileReader(gradeList);
BufferedReader bf = new BufferedReader(fr);
String line;
while ((line = bf.readLine()) != null){
System.out.println(line);
}
bf.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
}
Error line reads as follows:
java.io.FileNotFoundException: GradeList.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileReader.<init>(FileReader.java:72)
at ListCreator.getGrades(ListCreator.java:17)
at GradeStats.main(GradeStats.java:11)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
How about adding:
String curDir = System.getProperty("user.dir");
Print this out. It will tell you what the current working directory is. Then you should be able to see why it isn't finding the file.
Rather than allowing your code to throw, you could check to allow yourself to do something if the file isn't found:
File GradeList = new File("GradeList.txt");
if(!GradeList.exists()) {
System.out.println("Failed to find file");
//do something
}
Please run the below and paste the output:
String curDir = System.getProperty("user.dir");
File GradeList = new File("GradeList.txt");
System.out.println("Current sys dir: " + curDir);
System.out.println("Current abs dir: " + GradeList.getAbsolutePath());
The problem is you have specified only a relative file path and don't know what the "current directory" of your java app is.
Add this code and everything will be clear:
File gradeList = new File("GradeList.txt");
if (!gradeList.exists()) {
throw new FileNotFoundException("Failed to find file: " +
gradeList.getAbsolutePath());
}
By examining the absolute path you will find that the file is not is the current directory.
The other approach is to specify the absolute file path when creating the File object:
File gradeList = new File("/somedir/somesubdir/GradeList.txt");
btw, try to stick to naming conventions: name your variables with a leading lowercase letter, ie gradeList not GradeList

Categories