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.
Related
I'm working on a program that reads from a file with a custom extension I made. The idea is that an error report is created every time a file is read. The error report must be in whatever folder the source file was called from. The error file is a copy of the source file, but it has a line number at the beginning of each line and indicates at the end of the line if an error occurred at that line.
(I'm not trying to set up the numbering on this question, this question is just about creating the copy)
So for example, when I call my program from the command prompt:
C:\MyLocation>java =jar myJavaProgram.jar myFileToRead.CustomExtension
Asides from reading the file, it should also create a copy at the same location called myFileToRead-ErrorReport.txt
Additionally: If the source file has no extension, I have to assume that it's still the correct extension, so there won't always be a '.myCustomExtension' segment to replace into .txt
The problem is that I don't know how to grab the file name, because it's coming from the args list of the main method. I am using the following to read the file
public static void main(String[] args) throws FileNotFoundException {
try{
File inputFile = new File(args[0]);
Scanner sc = new Scanner(inputFile);
while(sc.hasNext()){
System.out.println(sc.nextLine());
}
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage());
System.out.println("File not found.");
}
}
So how can I get that file name to make something like
File errorReport = new File("./" + inputFileName + ".txt"); ?
First the code. The explanations appear after the code.
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("ERROR: Missing filename argument.");
}
else {
String filename = args[0];
if (filename.length() == 0) {
System.out.println("ERROR: Empty filename argument.");
}
else {
if (!filename.endsWith(".CustomExtension")) {
filename += ".CustomExtension";
}
String name = filename.substring(0, filename.indexOf(".CustomExtension"));
name += "-ErrorReport.txt";
File inputFile = new File(filename);
File directory = inputFile.getParentFile();
File errorReport = new File(directory, name);
System.out.println(errorReport.getAbsolutePath());
}
}
}
I make it a habit of checking the parameters. Hence I first check that the file name was supplied. If it was, then I check that it is not an empty string. Note that I have omitted some checks, for example checking whether the named file exists and is readable.
You wrote in your question that the file name argument may or may not include the .CustomExtension. Hence I check whether the supplied name ends with the required extension and append it if necessary. Now, since I know what the file name ends with, that means that the required part of the name is everything up to the extension and that's what the call to substring() gives me.
Once I have the required name, I just append the part that you want to append, i.e. -ErrorReport.txt.
Method getParentFile() in class java.io.File returns the directory that the file is located in. Hence I have the directory that the input file is in. Finally I can create the error report file in the same directory as the input file and with the desired file name. For that I use the constructor of class java.io.File that takes two parameters. Read the javadoc for details.
Note that creating a File object does not create the file. Creating an object to write to the file does, for example FileWriter or OutputStreamWriter.
Here is the code example to create a file, with filename passed from cmd line as argument and to get the same file name :
Class Demo{
public static void main(String[]args){
String path ="<path of file>"
String name= args[0];
File f = new File(path+name+".txt");
f.createNewFile(); //create file
System.out.println(f.getName()); // will give you the file name
}
}
cmd line : java -cp . Demo.java <filename>
Note : '.' used in the cmd if your class file is present in current dir
You can refer the code and modify to suit your requirement.
Hope this is what you are looking for.
I have looked through questions that have been posted here regarding this problem, and none of the solutions have been helpful. I found a link to this page http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#Scanner%28java.io.File%29
also, not helpful. I have looked through my text book, even copied a similar code straight from the book, and was again given the File Not Found Exception. The input.txt file is in the same folder as the program file, and I tried to use a specific path, also added this line to the code System.out.println(new File("C:/input.txt").getAbsolutePath());
it also did not help. I feel like I have more questions now than answers. The name of the file is correct, and case is correct. I did find that the .txt files are being saved in Word, so I went there and changed the format to plain txt file. Does it being saved as a Word document have something to do with this problem, or am I wasting time there?
Here is my code:
import java.util.Scanner;
import java.io.*;
import java.text.DecimalFormat;
public class FileRead
{
public static void main(String[] args) throws IOException
{
double count = 0;
double sum = count++;
double average = sum/count;
File fileObject = new File("C:/input.txt");
System.out.println(new File("C:/input.txt").getAbsolutePath());
Scanner fileIn = new Scanner (fileObject);
while (fileIn.hasNext())
{
count = fileIn.nextDouble();
sum = count++;
}
average = sum/count;
DecimalFormat df = new DecimalFormat("#0.00");
System.out.println("The total of the: " + count + "numbers entered are: "
+ sum + " and the average is: " + df.format(average));
}
}
C:/input.txt is telling the file system to look for a file called input.txt at the root of the hard drive, assuming C:/ is equivalent to C:\.
Is this where you are running the program in the root directory. If not, and there is no file called input.txt in the root director the program won't work as expected.
Try changing the the code as described by BlackCode, and/or removing the C:/
Typing pwd in a command window will tell you what directly you are in, and if its not the root of your hard drive the program can not find the file you are telling it too look for.
You need to escape the slash: "C://input.txt".
In file path change "/" to File.separator
Example:
File fileObject = new File("C:" + File.separator + "input.txt");
"The input.txt file is in the same folder as the program file": that means you only need "input.txt"
To see the files exactly with the names saved you can go to the command window and type dir at the location where you are looking for.
Alternately you can do that from within the program:
File f=new File(".");
String[] fs=f.list();
for(String s:fs) System.out.println(s);
If your file doesnt print then it's somewhere else.
Your code looks fine and it works fine on my Window 7 (although I had to change to administrator to create the c:\input.txt)
It is confusing that .getAbsolutePath() gives a value even if the file does not exist.
A better test is the following - it will print false if your file does not exist.
File fileObject = new File("c:/input.txt");
System.out.println(fileObject.exists());
Scanner fileIn = new Scanner (fileObject);
To be certain the file exists try this at the command line
echo 1 2 3 4 > input.txt
Then get rid of the full path and just use "input.txt" as the file name.
Use this :
Scanner fileIn = new Scanner ("C:/input.txt");
I'm making a program where I have to make a file and then deserialize the object in that file. When I name the file something, such as "contacts.dat", I get a FileNotFoundException.
The code is below:
public static void main(String[] args) {
String inputstring = Input.getString("Please enter the name of the file containing the contacts: ");
TreeMap< String, Contact > contactlist = null;
ObjectInputStream in;
try {
in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(inputstring)));
contactlist = (TreeMap< String, Contact >) in.readObject();
in.close();
}
catch(ClassNotFoundException | EOFException emptyexcptn) {
System.out.println("The file provided is currently empty.");
contactlist = new TreeMap< String, Contact >();
}
catch(IOException ioexcptn) {
ioexcptn.printStackTrace(System.out);
System.out.println("Error reading file: " + inputstring);
System.exit(1);
}
Here's what the exception prints:
java.io.FileNotFoundException: contacts.dat (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.(FileInputStream.java:138)
at java.io.FileInputStream.(FileInputStream.java:93)
at UnitEight.AssignmentEight.main(AssignmentEight.java:16)
Error reading file: contacts.dat
Your argument to new FileInputStream() is String inputstring = Input.getString("Please enter the name of the file containing the contacts: ");...if Input.getString returns the path for the file then you are pointing to the wrong path anyway.
Print the result of Input.getString()...if any and that would give you a clue what's going on there.
From the API docs -
Constructor Detail
FileInputStream
public FileInputStream(String name) throws FileNotFoundException
Creates a FileInputStream by opening a connection to an actual file, the file named by the path name name in the file system. A new FileDescriptor object is created to represent this file connection.
First, if there is a security manager, its checkRead method is called with the name argument as its argument.
If the named file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading then a FileNotFoundException is thrown.
Parameters:name - the system-dependent file name.Throws:FileNotFoundException - if the file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading.SecurityException - if a security manager exists and itscheckRead method denies read access to the file.
To summarize in to a working example:
When you are using the FileInputStream(String filename), try it by specifying the full (absolute) path to the file so your program can find it. Ex: if your text.dat file was on a shared drive Z: your String you would have to pass as a parameter to the constructor would be
"Z:\\text.dat" instead of using an OS specific slash character it is better to use File.separator in the above example it would look like "Z" + File.separator + "text.dat".
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.
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