change password of user account in java using text files? - java

I have a problem and hope to find a solution.
now i have created a simple program to change password of user account using text files in java.
now i should enter username of the account then change password of that account but there it shows me an error.
here is my code:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Objects;
import java.util.Scanner;
public class Test6 {
public static void main(String[] args)throws IOException {
String newPassword=null;
boolean checked = true;
File f= new File("C:\\Users\\فاطمة\\Downloads\\accounts.txt");// path to your file
File tempFile = new File("C:\\Users\\فاطمة\\Downloads\\accounts2.txt"); // create a temp file in same path
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
Scanner sc = new Scanner(f);
System.out.println("Enter account username you want to edit password?");
Scanner sc2 = new Scanner(System.in);
String username = sc2.next();
while(sc.hasNextLine())
{
String currentLine= sc.nextLine();
String[] tokens = currentLine.split(" ");
if(Objects.equals(Integer.valueOf(tokens[0]), username) && checked)
{
sc2.nextLine();
System.out.println("New Password:");
newPassword= sc2.nextLine();
currentLine = tokens[0]+" "+newPassword;
checked = false;
}
writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
sc.close();
f.delete();
boolean successful = tempFile.renameTo(f);
}
}
the error shows to me:
Exception in thread "main" java.lang.NumberFormatException: For input string: "HAMADA"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.valueOf(Integer.java:766)
at Test6.main(Test6.java:25)
the format of my text file is like that:
HAMADA 115599
JOHNY 4477100

Change Integer.valueOf(tokens[0]) on line 25 to just tokens[0].
In your code, you try to get the integer value of the username, when you should be getting its String representation. You do not need the Integer.valueOf(). (The error is thrown because you are trying to get the Integer representation of a non-integer type.)
On a side note, you should never have password-storing text files, especially when the passwords and the files are both unencrypted. Use a database instead.

Related

Java data storage in CSV

I tried to writting my user input in java to csv file but i dont know how to my username and password in a cell ,whenever i run my program my new username and new password gets overlapped in the same cell with my old username and old password.
package data1;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Data1 {
public static void main(String[] args) {
String name ;
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name: ");
name = sc.nextLine ();
System.out.println("Your Name is "+name );
String filepath = "C:\\Users\\Lenovo\\OneDrive\\Desktop\\Data.csv";
try
{
FileWriter fw = new FileWriter(filepath,true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
StringBuilder sb = new StringBuilder ();
String username = name;
String password = "123";
sb.append(username);
sb.append(",");
sb.append (password);
pw.print(sb.toString());
pw.flush();
pw.close();
JOptionPane.showMessageDialog(null, "Report saved");
}
catch(Exception E)
{
}
}
}
It looks like you have a good start. The issue I'm seeing is you're outputting the username and password so it looks like this:
username,password
However, next time it runs, you once again print the username and password without prepending a comma:
username,passwordusername2,password2
^ note there is no comma
You might try checking if there is already text in the CSV file and adding a comma before the new username and password if there is:
username,password,username2,password2
Two possibilities here:
Change new FileWriter(filepath,false);
Don't silently throw away any possible exception. If your code is crashing you won't even know it. Try adding "throw new RuntimeException(E);" to the exception body.

How to compare username password and secret code with text file to login java

Below my code is only to input data into text file now i have to make a new login form when user put username password and secret code it will logged in if wrong then error i put some data in text file using code below now i want to compare from text file and logged in i am making a java program on sublime i am newbie this is my assignment how to compare in simplest way with text file data, text file contains username password secret code in same line how to arrange that i am stuck i am trying from last 9 hours its assignment
import java.util.*;
import java.io.*;
public class Reg{
public static void main (String[]args)throws IOException {
Users p = new Users();
Scanner sc = new Scanner(System.in);
System.out.println("Enter username");
String uu = sc.nextLine();
p.setUser(uu);
System.out.println("Enter password");
String pp = sc.nextLine();
p.setPassword(pp);
System.out.println("Enter Secret number");
String ss = sc.nextLine();
p.setSecret(ss);
FileWriter fw = new FileWriter(file);
PrintWriter pw = new PrintWriter(fw);
pw = new PrintWriter(new FileWriter("output.txt", true));
pw.write(uu);
pw.write(pp);
pw.write(ss);
pw.close();
}
}
You already created the pw, don't need to create again and i write something in the code you read from it. I wish it will help you.
import java.awt.Color;
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.JFrame;
public class Reg{
public static void main (String[]args)throws IOException {
Users p = new Users();
String uu = "";
String pp = "";
String ss = "";
//I think you created a method in Users and say logined or something error.
While(Users.getLogin == false){
//***I don't know the Users class you made
Scanner sc = new Scanner(System.in);
System.out.println("Enter username");
uu = sc.nextLine();
p.setUser(uu);
System.out.println("Enter password");
pp = sc.nextLine();
p.setPassword(pp);
System.out.println("Enter Secret number");
ss= sc.nextLine();
p.setSecret(ss);
}
//Something like this
if(Users.getLogin == true){
//if you wanna write something to the file, u can use this.
FileWriter fw = new FileWriter("output.txt");
PrintWriter pw = new PrintWriter(fw);
pw.write(uu);
pw.write(pp);
pw.write(ss);
//if you wanna write line by line use writeln, not write.
pw.close();
}
}
}

Java Check Vaild File

Please help, I need help on how to check for valid file names.
Here is part of my program...
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class BookstoreInventory
{
public static void main(String[] args)throws IOException
{
//Vaiable declartions
int edition, quanity;
double pricePerBook;
String isbn, author, title, publisherCode;
int totalQuant = 0;
double total = 0;
double totalValue = 0;
double sumOfPriceBook = 0;
//Scanner object for keyboard input
Scanner keyboard = new Scanner(System.in);
//Get the file name from the user
System.out.print("Enter the name of the file: ");
String filename = keyboard.nextLine();
//Open the file and set delimiters
File file = new File(filename);
Scanner inputFile = new Scanner(file);
inputFile.useDelimiter("_|/|\\r?\\n");
}
}
So in my program I'm not sure how I would check to see if it's a valid file. For example, when the user enters "inventory" for the name of the file this will produce an error because the filename needs the .txt so the user should have entered "inventory.txt". So is there a way to adding the .txt to the name they entered? Or how do I check to see if a file is valid? Any help would be much appreciated.
You can try this:
if (!fileName.trim().toLowerCase().endsWith(".txt")) {
fileName+= ".txt";
}
Also, if you want to know if the file already exists or not:
File file = new File(filename);
// If file doesn't exist then close application...
if (!file.exists()) { System.exist(0); }
Hope this helps.
Try concatenating the user's input string by adding .txt. It should work.

read input from txt file names(one word) and (ints). write to output file the lists with ages then names

When finished output should be:
15 Michael
16 Jessica
20 Christopher
19 Ashley
etc.
I am not that good at this and would like any input whatsoever on how to get the int and strings to print line by line. I have avoided an array approach because I always have difficulty with arrays. Can anyone tell me if I am on the right track and how to properly parse or type cast the ints so they can be printed on a line to the output file? I have been working for days on this and any help would be much appreciated! Here is what I have so far.
import java.io.PrintWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class NameAgeReverse
{
public static void main (String[] args)
{
System.out.println("Programmed by J");
String InputFileName;
String OutputFileName;
Scanner keyboard = new Scanner(System.in);
System.out.print("Input file: ");
InputFileName = keyboard.nextLine();
System.out.print("Output file: ");
OutputFileName = keyboard.nextLine();
Scanner inputStream = null;
PrintWriter outputStream = null;
try
{
inputStream = new Scanner(new FileInputStream("nameAge.txt"));
outputStream =new PrintWriter(new FileOutputStream("ageName.txt"));
}
catch(FileNotFoundException e)
{
System.out.println("File nameAge.txt was not found");
System.out.println("or could not be opened.");
System.exit(0);
}
int x = 0;
String text = null;
String line = null;
while(inputStream.hasNextLine())
{
text = inputStream.nextLine();
x = Integer.parseInt(text);
outputStream.println(x + "\t" + text);
}
inputStream.close();
outputStream.close();
}
}
Here are my error messages:
Exception in thread "main" java.lang.NumberFormatException: For input string: "Michael"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at NameAgeReverse.main(NameAgeReverse.java:52)
text = inputStream.nextLine(); will read the whole line of text with both name and age. Assuming the format of every line in your input file is age name, you can do the following parse every line of text into desirable values. Note that this won't work out of the box with the rest of your code. Just a pointer:
text = inputStream.nextLine().split(" "); // split each line on space
age = Integer.parseInt(text[0]); // age is the first string
name = text[1];
This should work:
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class ReadWriteTextFile {
final static Charset ENCODING = StandardCharsets.UTF_8;
public static void main(String... aArgs) throws IOException{
List<String> inlines = Files.readAllLines(Paths.get("/tmp/nameAge.txt"), ENCODING);
List<String> outlines = new ArrayList<String>();
for(String line : inlines){
String[] result = line.split("[ ]+");
outlines.add(result[1]+" "+result[0]);
}
Files.write(Paths.get("/tmp/ageName.txt"), outlines, ENCODING);
}
}

How to display text written to an external text file on Java?

I was wondering because I made my program save data to an external program, but I need to know how to display on Java.
Here's the code:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class StoringInfo {
public static void main(String[] args) throws IOException {
Scanner keyboard=new Scanner(System.in);
System.out.print("\n Enter the customer's name: ");
String name1=keyboard.next();
System.out.print("\n Enter the customer's first part of the address: ");
String Address=keyboard.next();
System.out.print("\n Enter the rest of the address:");
String Address2=keyboard.next();
System.out.print("\n Enter the customer's E-mail: ");
String Email=keyboard.next();
System.out.print("Customer has been added to the list.");
File file = new File("CustomerData.txt");
FileWriter writer = new FileWriter(file, true);
PrintWriter output = new PrintWriter(writer);
output.println(name1);
output.println(Address);
output.println(Address2);
output.println(Email);
I was wondering if you use something like BufferedReader or another code?
output.close();
You can use a Scanner to read from files too.
File file = new File("CustomerData.txt");
Scanner fileReader = new Scanner(file);
And you can apply the knowledge you know about Scanners to this.
Alternatively you could use a BufferedReader (which is faster).
BufferedReader reader = new BufferedReader(new FileReader("CustomerData.txt"));
And use:
reader.readLine();
To read the next line.

Categories

Resources