Reading a file with scanner - java

EDIT: I ADDED A NEW PART to catch fileexception error
This is a pincheck program. I'm supposed to create a txt file with the following lines:
peter, 1212
john, 1234
mary, 0000
I then have to write a java program to prompt user for the file path of the txt file then key in their name and pin number. I'm able to compile my code but I don’t get the expected result when I type in the correct name and pin.
import java.util.*;
import java.io.*;
public class PINCheck {
public static void main(String[]args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter file path: ");
String filepath = s.nextLine();
File passwordFile = new File(filepath);
System.out.print("Enter name: ");
String name = s.nextLine();
System.out.print("Enter password: ");
String password = s.nextLine();
try {
Scanner sc = new Scanner(passwordFile);
while (sc.hasNext()) {
if (password.matches(".*[a-zA-Z]+.*")) {
System.out.println("You have entered a non-numerical PIN!");
} else if (sc.hasNext(name) && sc.hasNext(password)) {
System.out.println("You have logged in successfully.");
}else {
System.out.println("Login Failed.");
}
break;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

This line : Scanner sc = new Scanner("passwordFile"); implies that Scanner will scan from the String specified in the constructor and not the actual file.
Use Scanner sc = new Scanner(passwordFile); instead.
A similar mistake for File passwordFile = new File("filepath");.
Use it like File passwordFile = new File(filepath);
In both cases, pass the variable, not the string.

Related

writing files in java from user input

I'm trying to write a program which will take user input from a list of options then either:
write to a file
alter an existing file or
delete a file.
At the moment I'm stuck on just writing to the file from the user input. I have to use regex notation for each of the users input as seen in the snippet. Any help or guidance on what i could do will be highly appreciated, and yes there are a lot of errors right now. Thanks!
import java.io.*;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
private UserInput[] list;
class Input {
public static void main(String[] args) {
Scanner in = (System.in);
string Exit ="False";
System.out.println("person details");
System.out.println("");
System.out.println("Menu Options:");
System.out.println("1. Add new person");
System.out.println("2. Load person details ");
System.out.println("3. Delete person Entry");
System.out.print("Please select an option from 1-5\r\n");
int choice = in.nextLine();
if (choice == 1)
system.out.println("you want to add a new person deails.");
AddStudnet();
else if (choice == 2){
system.println("would you like to: ");
system.println("1. Load a specific entry");
system.println("2. Load ");
}
//Error checking the options
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
int input = Integer.parseInt(br.readLine());
if(input < 0 || input > 5) {
System.out.println("You have entered an invalid selection, please try again\r\n");
} else if(input == 5) {
System.out.println("You have quit the program\r\n");
System.exit(1);
} else {
System.out.println("You have entered " + input + "\r\n");
}
} catch (IOException ioe) {
System.out.println("IO error trying to read your input!\r\n");
System.exit(1);
}
}
}
//Scanner reader = new Scanner(System.in);{ // Reading from System.in
//System.out.println("Please enter your name: ");
//String n = reader.nextLine();
//}
// File file = new File("someFile.txt", True);
// FileWriter writer = new FileWriter(file);
// writer.write(reader);
// writer.close();
public static void addPerson(String args[]) throws IOException{
class input Per{
scanner in = new scanner (system.in);
system.out.print("Please enter you Name: ");
String name = in.nextLine()
final Pattern pattern = Pattern.compile("/^[a-z ,.'-]+$/i");
if (!pattern.matcher(name).matches()) {
throw new IllegalArgumentException("Invalid String");
//String Name = regex ("Name")
//regex below for formatting
system.out.println("Please enter your Job title:");
//String CourseNum = regex ("JobTitle");
system.out.println("Please enter your Town:");
//String Town = regex("Town");
system.out.println("Please enter your postcocde:");
//String postcocde = regex("postcocde");
system.out.println("Please enter your street:");
//String Street = regex ("Street");
system.out.println("Please enter your House Number:");
//String HouseNum = regex ("HouseNum");
}
}
//public static void
Is not clear that you look for " i'm stuck on just writing to the file"
here exemple on how to create/write to a file
String export="/home/tata/test.txt";
if (!Files.exists(Paths.get(export)))
Files.createDirectory(Paths.get(export));
List<String> toWrite = new ArrayList();
toWrite.add("tata");
Files.write(Paths.get(export),toWrite);
look at java tm
https://docs.oracle.com/javase/tutorial/essential/io/file.html
lio

Breaking a file down and rewriting it in java

I'm working on trying to break down this file that contains state abbreviations, state names, and zip codes. Some of the zip codes are only 3 digit zip codes and for formatting purposes have to be rewritten(Ex. 005 should be 005-005). What I need help with is separating the state names and abbreviations from the zip codes so that I can format the 3 digit zip codes into 6 digit zip codes.
The layout of the file is like this:
NY New York 005 063 090-149
etc with the rest of the states... (Notice how New York is a 2 part name and how it has a 3 digit zip code of 005 and 063. That needs to be rewritten as 005-005 and 063-063)
Here is my code:
public class ZipsReader {
public static void main(String[] args){
//Gets the file name and reads it
try {
//Prompts user for an input file
Scanner console = new Scanner(System.in);
System.out.println("Input file: ");
String inputFileName = console.next();
//Prompts user for an output file
//System.out.println("Output file: ");
//String outputFileName = console.next();
//PrintWriter out = new PrintWriter(outputFileName);
//Reads the selected file line for line
File selectedFile = new File(inputFileName);
Scanner in = new Scanner(selectedFile);
while (in.hasNextLine()) {
String line = in.nextLine();
Scanner in2 = new Scanner(line);
//Reads the selected file word for word
while (in2.hasNext()){
String state = in2.isLetter();
String word = in2.next();
if (word.matches("\\d{3}-\\d{3}")){
System.out.println(word);
}
if (word.matches("\\d{3}")){
System.out.println(word + "-" + word);
}
}
in2.close();//closes the word scanner
}
console.close();//closes the file opener scanner
in.close();//closes the line scanner
//out.close();//closes the print writer
}
//Prints out message if file cant be found
catch (FileNotFoundException e) {
System.out.println("Sorry the file could not be found.");
}
//Needed to compile
finally {
}
}
}
The .matches String method works for getting the zip codes but I am not sure how to pick out the state abbrev. and names separately from the zip codes.
Right now I am just doing it to the console for time saving reasons for the time being but I will modify it to write to another file when I get this figured out.
Thanks for the help in advance
You can try this:
public class ZipReader {
public static void main(String[] args) {
//Gets the file name and reads it
try {
//Prompts user for an input file
Scanner console = new Scanner(System.in);
System.out.println("Input file: ");
String inputFileName = "G:\\test.txt";
//Prompts user for an output file
//System.out.println("Output file: ");
//String outputFileName = console.next();
//PrintWriter out = new PrintWriter(outputFileName);
//Reads the selected file line for line
File selectedFile = new File(inputFileName);
Scanner in = new Scanner(selectedFile);
String states="";
while (in.hasNextLine()) {
String line = in.nextLine();
Scanner in2 = new Scanner(line);
//Reads the selected file word for word
while (in2.hasNext()) {
//String state = in2.isLetter();
String word = in2.next();
if (word.matches("\\d{3}-\\d{3}")) {
System.out.println(word);
}
else if (word.matches("\\d{3}")) {
System.out.println(word + "-" + word);
}
else if(word.matches("[A-Z]{2}")){
System.out.println(word);
}
else{
states=states+word+" ";
}
}
System.out.println(states+"\n");
states="";
in2.close();//closes the word scanner
}
console.close();//closes the file opener scanner
in.close();//closes the line scanner
//out.close();//closes the print writer
} //Prints out message if file cant be found
catch (FileNotFoundException e) {
System.out.println("Sorry the file could not be found.");
} //Needed to compile
finally {
}
}
}

Java Text file logon

Does anyone have any ideas how I can complete my code for when a user logs in using their username/password for the first time it notify s them that a new account has been created and then create a text file, with the user/pass in it. Whilest having it proceed to let users with accounts log in as usual.
Here is my code so far. It will read a text file for the username but it will receive a run time error on pass.
import java.util.Scanner;
public class Login{
public static void main (String[] args) {
Scanner scan = new Scanner("Libraries/Documents/userPass.txt");
Scanner keyboard = new Scanner(System.in);
String user = scan.nextLine();
String pass = scan.nextLine();
String inpUser = keyboard.nextLine();
String inpPass = keyboard.nextLine();
if(inpUser.equals(user) && inpPass.equals(pass)){
System.out.print("Welcome");
}
else{
System.out.print("Password or Username is incorrect");
}
}
}
You would better use a XML file to store the usernames and passwords. It's easy to modify and read. And also you can trigger an error messages like User Already Exist if that username contains in XML file. Format will looks like(You can change this format as your choice),
<users>
<user id="1">
<username>User 1</username>
<password>User 1 password</password>
</user>
<user id="2">
<username>User 2</username>
<password>User 2 password</password>
</user>
</users>
and try to encrypt the password for more security. You can check with the username, if signing in user is already exist or not. If not exist, you can write it into the XML and notify a message like A new account has been created.
Here is the tutorial of XML reading and writing.
Read and Write XML in Java
Here is the modification of your code.
import java.io.*;
import java.util.Scanner;
public class Login {
public static void main(String[] args) {
Scanner scan = null;
File file = new File("Libraries/Documents/userPass.txt");
try {
scan = new Scanner(file);
FileWriter fw = new FileWriter(file, true); //the true will append the new data
Scanner keyboard = new Scanner(System.in);
String user = "";
String pass = "";
while (scan.hasNext()) {
user = scan.nextLine();
pass = scan.nextLine();
}
String inpUser = keyboard.nextLine();
String inpPass = keyboard.nextLine();
if (inpUser.equals(user) && inpPass.equals(pass)) {
System.out.print("Welcome");
} else {
System.out.println("Password or Username is incorrect");
fw.write("\n" + inpUser + " " + inpPass);//appends the string to the file
fw.close();
System.out.println("New Account has been created!");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Hope this will help.
Code:
int i = 0;
String fileName = "C:\\Users\\J Urguby\\Documents"
+ "\\NetBeansProjects\\UserPassPageScanner\\src\\userpasspagescanner\\userPass.txt";
File file = new File(fileName);
while (i == 0) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your user name plz:");
String user = keyboard.next();
System.out.println("Enter your password plz");
String pass = keyboard.next();
try (Scanner input = new Scanner(file)) {
while (input.hasNextLine()) {
String[] line = input.nextLine().split(" ");
if (line[0].equals(user) && line[1].equals(pass)) {
System.out.print("Welcome");
i = 1;
}
}
if(i==0) System.out.println("Password or Username is incorrect");
} catch (Exception e) {
System.out.println(e);
}
}
}
Output:
File Content:
kick 123456
hello 234568
Note: if you need any clarification please let me know
Let's start with, Scanner scan = new Scanner("Libraries/Documents/userPass.txt");, which isn't doing what you think it is. Instead of reading the file userPass.txt, it is using the String value as the contents for the Scanner...
Instead you should be using Scanner(File) instead...
In this case, all you really need to do is check for the existence of the File to determine if it's a new user or not, for example...
File passes = new File("userPass.txt");
try {
String user = null;
String pass = null;
if (passes.exists()) {
try (Scanner scan = new Scanner(passes)) {
user = scan.nextLine();
pass = scan.nextLine();
}
}
if (user == null) {
System.out.println("Welcome new user, please enter the user name and password for your new account...");
} else {
System.out.println("Welcome back user, please enter your user name and password...");
}
Scanner keyboard = new Scanner(System.in);
String inpUser = keyboard.nextLine();
String inpPass = keyboard.nextLine();
if (user == null) {
// Create user account...
} else {
if (inpUser.equals(user) && inpPass.equals(pass)) {
System.out.print("Welcome");
} else {
System.out.print("Password or Username is incorrect");
}
}
} catch (IOException ex) {
ex.printStackTrace();
}

File output with loop check and try catch block

Having a bit of trouble with file outputs and using try/catch. I'm trying to basically say that if the user inputs an existing filename, keep looping until valid filename is entered. However, i cant seem to get it to work. Any hints on where im going wrong? Tried moving the initial prompt around try block but wouldnt that make the scope only available in the try block? So essentially, i should have the prompt outside so its available to all the try/catch blocks? Not sure though.
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
public class TestAccountWithException
{
public static void main(String[] args) throws IOException
{
// variable declaration
String fileName;
String firstName;
String lastName;
double balance;
int id = 1122;
final double RATE = 4.50;
Scanner input = new Scanner(System.in);
System.out.print("Please enter file name: ");
fileName = input.next();
File fw = new File(fileName);
try
{
// check if file already exists
while(fw.exists())
{
System.out.print("File already exists. Enter valid file name: ");
fileName = input.next();
fw = new File(fileName);
}
System.out.print("Enter your first name: ");
firstName = input.next();
System.out.print("Enter your last name: ");
lastName = input.next();
System.out.print("Input beginnning balance: ");
balance = input.nextDouble();
// pass object to printwriter and use pw to write to the file
PrintWriter pw = new PrintWriter(fw);
// print to created file
pw.println(firstName);
pw.println(lastName);
pw.println(balance);
pw.println(id);
pw.println(RATE);
pw.close();
// System.out.print("Run program? (1) Yes (2) No: ");
// cont = input.nextInt();
} catch (IOException e) {
e.printStackTrace();
}
} // end main
} // end class
You may prefer to use java.nio.file. With this java 7 package, you can use as
while(true) {
String fileName = input.next();
Path path = Paths.get(fileName);
if (Files.exists(path)) {
try {
// file exists
// your operations
} catch {
}
break;
} else {
// not found
fileName = input.next();
}
}

How can I rename a file with the name of the original and delete the original file?

import java.io.*;
import java.util.*;
import java.lang.*;
public class FileWritingApp{
public static void main(String[] args) {
String inputFilename = "marks.txt"; // It expects to find this file in the same folder as the source code
String outputFilename = "fakemarks.txt"; // The program will create this file
PrintWriter outFile;
String name,choice;
int mark1,mark2;
boolean flag=false;
Scanner input = new Scanner(System.in);
System.out.println("Do you want to add or find a student?");
try {
outFile = new PrintWriter(new FileWriter(outputFilename),true); // create a new file object to write to
File file = new File(inputFilename); // create a file object to read from
File file1 = new File(outputFilename);
Scanner scanner = new Scanner(file); // A scanner object which will read the data from the file passed in.
choice= input.nextLine();
switch(choice){
case "f":
System.out.println("Enter a name:");
name=input.nextLine();
while (scanner.hasNextLine()) { // This will loop until there are no more lines to read
String line = scanner.nextLine();
if(line.contains(name)){
System.out.println("Enter the first mark set:");
mark1=input.nextInt();
System.out.println("Enter the second mark set:");
mark2=input.nextInt();
line=name+", " + mark1 +", "+ mark2;
outFile.println(line);
flag=true;
} else {
outFile.println(line);
}
}
if(flag==false){
System.out.println('"'+name+'"'+" wasn't found");
}
break;
case "a":
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
outFile.println(line);
}
System.out.println("Enter a name:");
name=input.nextLine();
System.out.println("Enter the first mark set:");
mark1=input.nextInt();
System.out.println("Enter the second mark set:");
mark2=input.nextInt();
outFile.println(name+", " + mark1 +", "+ mark2);
break;
}
***scanner.close();
outFile.close();
if(file1.renameTo(file)){
System.out.println("rename succesful");
} else {
System.out.println("rename unsuccesful");
}
if(file.delete()){
System.out.println("delete succesful");
} else {
System.out.println("delete unsuccesful");
}***
}catch (IOException e) {
e.printStackTrace();
}
}
}
What I am having a problem with is that every time I run the program it returns false for changing the name of the new file to the original file and deleting the original file itself. I would appreciate if someone posted some code to solve this. I have highlighted the code that outputs feedback above.

Categories

Resources