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/
Related
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 new to Stack Overflow and fairly new to programming, so hopefully this makes sense. I am writing a java program that creates a file in a specific directory. My program works on Windows and creates a file in the right location, but it does not work on Mac. I have tried changing the backslashes to a single forward slash, but that doesn't work. How should I change the code so that it works for Mac or ideally for both? I've put some of the code below.
Thanks in advance!
Class that creates new path for file:
try{
//Create file path
String dirpath = new ReWriterRunner().getPath()+"NewFiles";
//Create directory if it doesn't exist
File path = new File(dirpath);
if (!path.exists()) {
path.mkdir();
}
//Create file if it doesn't exist
File readme = new File(dirpath+"\\README.md");
if (!readme.exists()) {
readme.createNewFile();
}
Method that gets user input on where to put file:
public static String getPath(){
String s;
Scanner in = new Scanner(System.in);
System.out.println("Enter the directory name under which the project files are stored.");
System.out.println("Example: C:\\Users\\user\\work\\jhipstertesting)");
System.out.println("Use double slashes when typing.");
s = in.nextLine();
return s;
}
you can use system properties to identify the system you are currently operating on ..
more info at https://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html
but i would prefer using NIO. but that is your choice
https://docs.oracle.com/javase/tutorial/essential/io/fileio.html
Forward slash "/" must be used to get the file path here. for ex.> Use:
File f = new File("/Users/pavankumar/Desktop/Testing/Java.txt");
f.createNewFile();
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.
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 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.