Check if a .txt file exists. FileWriter.exists method not working - java

SOLVED!!! Thanks for the hand guys got it working. Appreciate it!
I'm writing a program that has user name and password input. I am trying to check if a file exists for a user if the user puts in a user name that already exists when they create a user name and password.
The .exists method isn't working and I cant figure it out. Error cannot find symbol comes back. I've changed things, moved things around and got it down to one error. Tried using loops as well as if statements but using if gets me to only one error .Any help would be great.
import java.util.Scanner;
import java.io.*;
class UserData
{
public static void main ( String[] args ) throws IOException
{
Scanner kb = new Scanner(System.in);
System.out.println("Do you have an account? Yes or No: ");
String answer = kb.next().trim();
if ((answer.startsWith("N")) || (answer.startsWith("n")))
{
System.out.println("Create user name: ");
String user = kb.next().trim();
String fileName = user + ".txt";
FileWriter userData = new FileWriter(fileName);
if (userData.exists())
{
System.out.println("User already exists");
System.out.println("Create user name: ");
user = kb.next().trim();
fileName = user + ".txt";
userData = new FileWriter(fileName);
}
System.out.println("Create Password: ");
String ps = kb.next().trim();
userData.write(user + " ");
userData.write(ps);
userData.close();
}
else if ((answer.startsWith("Y")) || (answer.startsWith("y")))
{
System.out.println("Enter user name: ");
String user = kb.next().trim();
System.out.println("Enter Password: ");
String ps = kb.next().trim();
String fileName = user + ".txt";
Scanner inFile = new Scanner(new File(fileName));
String userName = inFile.next();
String password = inFile.next();
// If ((userName != user) || (password != ps))
// {
// System.out.println("User Not Found");
// System.out.println("Enter user name: ");
// String user = kb.next().trim();
//
// System.out.println("Enter Password: ");
// String ps = kb.next().trim();
//
// String fileName = user + ".txt";
// Scanner inFile = new Scanner(new File(fileName));
//
// String userName = inFile.next();
// String password = inFile.next();
// }
// else
// {
System.out.println("User Found");
// }
}
}}

You have compilation error here:
FileWriter userData = new FileWriter(fileName);
if (userData.exists())
Change it to:
File userDataFile = new File(fileName);
if (userDataFile.exists())
and of course:
FileWriter userData = new FileWriter(userDataFile);
userData.write(user + " ");
userData.write(ps);
userData.close();
If file doesn't exist anyway, you might be looking in a wrong directory. Try to add this:
System.out.println(new File(fileName).getAbsolutePath());
And check yourself if the file available on the printed path.

Related

Can't store inputs from JTextField to filewriter

I'm trying to make a phone directory where the user has to enter multiple inputs using JTextField. I also have a search option that will search the inputted name from the directory in filewriter and I just can't seem to store my inputs in the filewriter. This is my initial code
public static void main(String[] args) throws Exception {
Scanner scan = new Scanner(System.in);
int menu = 0;
boolean quit = false;
do{
String input = JOptionPane.showInputDialog(null,"Telephone Directory Management System"
+ "\n1. Add a Student"
+ "\n2. Search"
+ "\n3. Sort Data"
+ "\n4. List of all data"
+ "\n5. Exit"
+ "\n\nPlease enter your choice:","Main Menu",JOptionPane.QUESTION_MESSAGE);
menu = Integer.parseInt(input);
switch (menu) {
case 1:
JTextField student = new JTextField();
JTextField name = new JTextField();
JTextField address = new JTextField();
JTextField phone = new JTextField();
Object[] fields = {
"Enter Student ID:",student,
"Enter Name:",name,
"Enter Address:",address,
"Enter Phone No.:",phone};
int add = JOptionPane.showConfirmDialog(null,fields,"Add a Student",JOptionPane.OK_CANCEL_OPTION);
if (add == JOptionPane.OK_OPTION)
{
String student1 = student.getText();
String name1 = name.getText();
String address1 = address.getText();
String phone1 = phone.getText();
FileWriter fw = new FileWriter(new File("directory.txt"), true);
BufferedWriter out = new BufferedWriter(fw);
out.write(student1 + " " + name1 + " " + address1 + " " + phone1);
out.newLine();
}
break;
case 2:
input = JOptionPane.showInputDialog(null,"Enter name to search information:","Search",JOptionPane.OK_CANCEL_OPTION);
File f = new File("directory.txt");
try {
BufferedReader freader = new BufferedReader(new FileReader(f));
String s;
while ((s = freader.readLine()) != null) {
String[] st = s.split(" ");
String id = st[0];
String nm = st[1];
String add1 = st[2];
String phoneNo = st[3];
if (input.equals(nm)) {
JOptionPane.showMessageDialog(null,"Student ID: "+id+"\nName: "+nm+"\nAddress: "+add1+"\nPhone No.: "+phoneNo+"","Information",JOptionPane.QUESTION_MESSAGE);
}
}
freader.close();
} catch (Exception e) {
}
break;
I tried using scanner before and it does store my inputs but I need to use JOptionPane in this one. Thank you so much to anyone that can help me in this.
You should close the BufferedWriter after writing into it, like this
out.close()
If you don't do this the BufferedWriter won't flush what you've written into it to the underlying stream.

Comparing user input with text file (reading text file)

Im having trouble getting the program to read the info in a text file and compare it to user input. If the input and text match a menu will then be displayed if not the user will be locked out. I heard of a buffer line, but I'm not sure how it works. Any help will be appreciated!!
import java.util.Scanner;
import java.io.*;
public class test123{
public static void main(String[] args)throws IOException {
Scanner sc1 = new Scanner (System.in);
System.out.println("Please enter correct credentials to log in");
System.out.println("Username: ");
System.out.println("Password: ");
String userName = sc1.nextLine();
String passWord = sc1.nextLine();
File inFile = new File ("employee.txt");
while (sc1.hasNextLine())
{
Scanner sc = new Scanner (inFile);
String [] arrayName= new String [4];
String uName = arrayName[0];
String pWord = arrayName[1];
String line = sc.nextLine();
line = sc.nextLine();
if(userName.equals(uName) && passWord.equals(pWord))
{
System.out.println("Welcome " + userName + "!");
System.out.println("Menu: ");
System.out.println("\t1) Account");
System.out.println("\t2) Payroll");
System.out.println("\t3) Attendance Report");
System.out.println("\t4) Service Desk");
}
}
}
}
Your Scanner sc = new Scanner(inFile); should be outside your while loop.
Also check out this resource : https://www.geeksforgeeks.org/different-ways-reading-text-file-java/
If I understand correctly, you are checking if a user's username and password is correct or not!. This might work
public static void main(String[] args)throws IOException {
Scanner sc1 = new Scanner (System.in);
System.out.println("Please enter correct credentials to log in");
System.out.println("Username: ");
System.out.println("Password: ");
String userName = sc1.nextLine();
String passWord = sc1.nextLine();
File inFile = new File ("employee.txt");
Scanner sc = new Scanner (inFile);
String uName = sc.nextLine();
String pWord = sc.nextLine();
sc.close();
if(userName.equals(uName) && passWord.equals(pWord))
{
System.out.println("Welcome " + userName + "!");
System.out.println("Menu: ");
System.out.println("\t1) Account");
System.out.println("\t2) Payroll");
System.out.println("\t3) Attendance Report");
System.out.println("\t4) Service Desk");
}
else {
System.out.println("Error.!");
}
}
Well if you had empty lines in file or no text in file etc., this will not work as expected.

Call the exact value from text File

Hi guys need help for my mini project for schools. How do i compare the user input and match to my database in text file. this is like validity for username and password. I want to call the second line on my data base using account Number and pin.
this is my data base.
0,admin,adminLastName,123456,123456
1,user,userLastName,1234567,123456
0 = id
admin = name
adminLastName = Last Name
1234567 = accountNumber
123456 = pin
and this is my code.
package atm;
import java.io.File;
import java.util.Scanner;
public class Login {
static void verifyLogin(String name, String lastName, String userAccountNumber, String userPin, String filePath){
Scanner inputData = new Scanner(System.in);
boolean isFound = false;
String tempAccountNumber = "";
String tempPin = "";
System.out.print("\nAccount Number: ");
userAccountNumber = inputData.next();
System.out.print("\nPIN: ");
userPin = inputData.next();
try{
Scanner readTextFile = new Scanner(new File("myDataBase.txt")).useDelimiter("[,\n]");
while (readTextFile.hasNext() && !isFound){
tempAccountNumber = readTextFile.next();
tempPin = readTextFile.next();
if (tempAccountNumber.trim().equals(userAccountNumber.trim()) && tempPin.trim().equals(userPin.trim())){
isFound = true;
System.out.println("Welcome " + name+ " " +lastName);
System.out.println("\nLogin Successfully!");
}
else {
System.out.println("You have entered your PIN or ACCOUNT NUMBER incorrectly. Please check your PIN or ACCOUNT NUMBER and try again.\n If you don't have account yet please go to SignUp page!\n");
myMain mainMenu = new myMain();
mainMenu.inputKeyboard();
}
}
readTextFile.close();
}
catch (Exception e){
}
inputData.close();
}
}
If your textfile contains 1 user per line, and you split it with ',' then you can take each line like you do, then split that line into a string[] array and check if i.e. the name corresponds to 'admin'.
public class Main {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
Boolean loggedin = false;
String fileName = "accounts.txt";
String line = null;
System.out.println("What's your username?");
String tempUsername = input.nextLine();
System.out.println("What's your password?");
String tempPassword = input.nextLine();
try {
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
String[] currAccount = line.split(",");
if (currAccount[1].equals(tempUsername) && currAccount[4].equals(tempPassword)) {
loggedin = true;
System.out.println("You have successfully logged in!");
}
}
bufferedReader.close();
}
catch(FileNotFoundException ex) {
ex.printStackTrace();
// Let's create it if file can't be found or doesn't exist, but let's ask first.
String answer;
System.out.print("File not found, do you want to create it? [Y/n]: ");
answer = input.nextLine();
if (answer.equalsIgnoreCase("y")) {
try {
FileWriter fileWriter = new FileWriter(fileName);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
System.out.println("File has been created!");
} catch (IOException exc) {
exc.printStackTrace();
}
} else {
System.out.println("File was not created!");
}
}
catch(IOException ex) {
ex.printStackTrace();
}
if (!loggedin) {
System.out.println("Your login combination did not exist.");
}
}
}
Please note, I haven't commented a lot, but it should still make sense.
After splitting remember that you start at array index 0, and not 1. So at index 1 the name on the account will be.
Goodluck.

java keep trying until there are no more filenotfoundexception

I was trying to write code which would read an input file and create an output file. But when I tried to add a try until a correct input file name is input, I had problems. It shows not proper filenotfound exception is in try....
public static void main(String[] args) throws FileNotFoundException
{
//prompt for the input file name
Scanner in = new Scanner(System.in);
//keep trying until there are no more exceptions
//boolean done = false;
String inputfilename = " ";
while (!done)
{
try
{
System.out.print("Input file name (from your computer): ");
inputfilename = in.next();
done = true;
}
catch (FileNotFoundException exception)
{
System.out.println("****** ERROR ******\nCannot locate the input file '" + inputfilename + "' on your computer - please try again.");
}
}
//prompt for the output file name
System.out.print("What would you like to call your output file: ");
//use outputfilename variable to hold input value;
String outputfilename = in.next();
//construct the Scanner and PrintWriter objects for reading and writing
File inputfile = new File(inputfilename);
Scanner infile = new Scanner(inputfile);
PrintWriter out = new PrintWriter(outputfilename);
//read the input and write the output
out.println("Here is the class average for mstu4031:\n");
double totalgrade = 0;
double number = 0;
while (infile.hasNextDouble())
{
double grade = infile.nextDouble();
out.println("\n");
out.printf("%.1f\n",grade);
number++;
totalgrade = totalgrade + grade;
}
//print numbers and average in output file
out.println("\n\n");
out.printf("\nNumber of grades: %.1f",number);
//calculate average
double average = totalgrade/number;
out.println("\n\n");
out.printf("\nAverage: %.2f",average);
finally
{
in.close();
out.close();
}
}
There is no method in your try block that may throw a FileNotFoundException.
Try to instantiate your Scanner in the try block. It will throw the expected FileNotFoundException if the filename read from stdin does not exist:
String inputfilename = null;
Scanner infile = null;
while (!done)
{
try
{
System.out.print("Input file name (from your computer): ");
inputfilename = in.next();
infile = new Scanner(new File(inputfilename));
done = true;
}
catch (FileNotFoundException exception)
{
System.out.println("****** ERROR ******\nCannot locate the input file '" + inputfilename + "' on your computer - please try again.");
}
}
Wrong here. You are only receiving input without checking if the file actually exist. Every valid inputs will let you get out of the loop.
if(new File(inputfilename).exist()){
done = true;
}else{
System.out.println("****** ERROR ******\nCannot locate the input file '" + inputfilename + "' on your computer - please try again.");
}
You can only catch an exception if something in the try block may throw an exception.
However, you should test for existence of a file with File.exists(), instead of catching an exception.
File file;
do {
System.out.print("Input file name (from your computer): ");
file = new File(in.next());
} while (!file.exists());
Opening a file may throw an Exception. That's Why you need to put them inside try block. You have put only reading the input part inside try-catch block
Hope this code works properly:
//prompt for the input file name
Scanner in = new Scanner(System.in);
//keep trying until there are no more exceptions
//boolean done = false;
String inputfilename = " ";
while (!done)
{
try
{
System.out.print("Input file name (from your computer): ");
inputfilename = in.next();
done = true;
//prompt for the output file name
System.out.print("What would you like to call your output file: ");
//use outputfilename variable to hold input value;
String outputfilename = in.next();
//construct the Scanner and PrintWriter objects for reading and writing
File inputfile = new File(inputfilename);
Scanner infile = new Scanner(inputfile);
PrintWriter out = new PrintWriter(outputfilename);
//read the input and write the output
out.println("Here is the class average for mstu4031:\n");
double totalgrade = 0;
double number = 0;
while (infile.hasNextDouble())
{
double grade = infile.nextDouble();
out.println("\n");
out.printf("%.1f\n",grade);
number++;
totalgrade = totalgrade + grade;
}
//print numbers and average in output file
out.println("\n\n");
out.printf("\nNumber of grades: %.1f",number);
//calculate average
double average = totalgrade/number;
out.println("\n\n");
out.printf("\nAverage: %.2f",average);
}
catch (FileNotFoundException exception)
{
System.out.println("****** ERROR ******\nCannot locate the input file '" + inputfilename + "' on your computer - please try again.");
}
}
finally
{
in.close();
out.close();
}

I can't display a name from.txt file with a line number in the console

I have a Names.txt file I created with 4 names,bill,dave,mike, andjim
I can enter the file name and I can enter the name to search, for example dave above and then the console should return "dave appears on line 2 of Names.txt". Instead it returns "dave does not exist", which would be correct if it is not one of the four names. What mistake I am making in my while loop below?
public class names {
public static void main(String[] args) throws IOException {
String friendName; // Friend's name
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Get the filename.
System.out.print("Enter the filename: ");
String filename = keyboard.nextLine();
// Open the file.
File file = new File(filename);
Scanner inputFile = new Scanner(file);
// Get the name of a friend.
System.out.print("Enter name to search: ");
friendName = keyboard.nextLine().toLowerCase();
int lineNumber = 1;
while (inputFile.hasNextLine()) {
if ("friendName".equals(inputFile.nextLine().trim())) {
// found
String line = inputFile.nextLine();
System.out.println("friendName" + " appears on line " + lineNumber + " of Names.txt");
lineNumber++;
//break;
} else {
// not found
System.out.println(friendName + " does not exist. ");
break;
}
}
// Close the file.
inputFile.close();
}
}
Remove the quotes from friendName and use the actual variable which you read in from the file:
int lineNumber = 1;
booelan found = false;
while (inputFile.hasNextLine()) {
String nextLine = inputFile.nextLine().trim();
if (friendName.equals(nextLine)) {
// found
found = true;
break; // name is found, no point in searching any further
}
lineNumber++; // always increment the line number
}
if (found) {
System.out.println(friendName + " appears on line " + lineNumber + " of Names.txt");
}
else {
System.out.println(friendName + " does not exist. ");
}
I also changed the way you use your Scanner. In your original code, you were calling Scanner.nextLine() twice in the case of a match with the friend name. This would cause the scanner to advance two lines which is not what you want.
package com.stackoverflow;
import java.io.*;
import java.util.*;
public class Names
{
public static void main(String[]args) throws IOException
{
String friendName; // Friend's name
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Get the filename.
System.out.print("Enter the filename: ");
String filename = keyboard.nextLine();
// Open the file.
File file = new File(filename);
Scanner inputFile = new Scanner(file);
// Get the name of a friend.
System.out.print("Enter name to search: ");
friendName = keyboard.nextLine().toLowerCase();
int lineNumber = 0;
Boolean isFound = false;
while(inputFile.hasNextLine()){
lineNumber++;
String line = inputFile.nextLine();
if(line.trim().contains(friendName)){
System.out.println(friendName + " appears on line " + lineNumber + " of Names.txt");
}
}
if(!isFound){
System.out.println("given friend name "+friendName+" not exists in the file");
}
// Close the file.
inputFile.close();
} }

Categories