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".
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 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.
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/
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.
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