Java data storage in CSV - java

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.

Related

Java program to compare two text files, then replace variables found in the first text file with those in the 2nd file into a 3rd file

So I would like to ask if there is any way to modify the code I currently have in order to make it so it only replaces certain parts of the text file.
Let's say I have a text file called TestFile1 that contains
A = Apple
B = Banana
C = Carrot
D = Durian
And another called TestFile2 which contains
A = Art
C = Clams
What I would like to happen is that the code should be able to compare the two text files and if it finds that there are two variables that match, the output file which would be TestFile3 would look like this
A = Art
B = Banana
C = Clams
D = Durian
Also, I would like to make it dynamic so that I don't have to change the code every single time that the variables are changed so it can be used for other text files.
At the moment, I currently only have this code, but what it only does is that it just fully replaces TestFile2 with TestFile1 entirely, which is not what I intend to happen.
import java.nio.file.Paths;
import java.nio.file.Path;
import java.nio.file.Files;
import java.nio.file.OpenOption;
import java.nio.charset.Charset;
import java.io.*;
import java.util.Scanner;
public class FindAndReplaceTest {
static void replaceTextFile(String fileName, String target, String replacement, String toFileName) throws IOException
{
Path path = Paths.get(fileName);
Path toPath = Paths.get(toFileName);
Charset charset = Charset.forName("UTF-8");
BufferedWriter writer = Files.newBufferedWriter(toPath, charset);
Scanner scanner = new Scanner(path, charset.name());
String line;
while (scanner.hasNextLine()) {
line = scanner.nextLine();
line = line.replaceAll(target, replacement);
writer.write(line);
writer.newLine();
}
scanner.close();
writer.close();
}
public static void main(String[] args) throws IOException{
replaceTextFile("C:\\Users\\LS1-10\\Documents\\TestFile2.txt", "Write", "Read", "C:\\Users\\LS1-10\\Documents\\TestFile1.txt");
/*
System.out.println("Note: Make sure files to merge are in the same directory as this program!");
Scanner in = new Scanner(System.in);
String output, file1name, file2name;
System.out.print("Enter output file name: ");
output = in.nextLine();
PrintWriter pw = new PrintWriter(output + ".txt");
System.out.print("Enter name of first file: ");
file1name = in.nextLine();
BufferedReader br = new BufferedReader(new FileReader(file1name + ".txt"));
String line = br.readLine();
System.out.print("Enter name of second file: ");
file2name = in.nextLine();
br = new BufferedReader(new FileReader(file2name + ".txt"));
line = br.readLine();
pw.flush();
br.close();
pw.close();
System.out.println("Replaced variables in " + file1name + ".txt with variables in " + file2name + ".txt into " + output + ".txt"); */
}
}
I commented out the part of the psvm that would ask for user input on what the file names would be because I just took it from a previous program that I made so all I need is something that would compare the two files and make the output appear as intended. Any help would be appreciated. Thank you!
The most elegant way, given everything fits into memory would be to:
deserialize file2 to a map
upon reading file1, check if the variable has an associated value in the map, and replace if needed before outputing to file3.

The user must get out of while loop when he/she press enter in a new line. but it does not work and it keeps going to new lines

I need to do the following exercise:
a) Make a new text file
b) Put the user's input into that text file
c) we must save all user's input while user keeps typing but as soon as user pressing Enter in a new line (When an empty string is sent) the user must get out of the program.
For coding this issue I have write the following codes, but when
I try it by myself so I am stuck at while loop, cant get out when I sending empty string.
So could anyone help with a solution for this issue?
Thanks
I have tried some of the solutions I have found on youtube like making if statement inside the while loop or adding the code that takes the input of the user inside the loop's condition.
So I do not know what to do at the next stage.
I tried to see the console window via the Eclipse output.
import java.io.*;
import java.util.Scanner;
public class lesson {
public static void main(String[] args) throws IOException {
File file = new File("mytext.txt");
if (file.exists() == false) {
file.createNewFile();
}
PrintWriter pw = new PrintWriter(file);
System.out.println("Enter a text here: ");
String str;
while (true) {
Scanner input = new Scanner(System.in);
str = input.next();
pw.println();
if (str.equals(null)) {
break;
}
}
pw.close();
System.out.println("Done");
}
}
The user must get out of the loop when he/she sends an empty string. and the writing to the file must be finished.
First the code, then the explanation...
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Lesson {
public static void main(String[] args) {
File file = new File("mytext.txt");
try (Scanner input = new Scanner(System.in);
PrintWriter pw = new PrintWriter(file)) {
System.out.println("Enter a text here: ");
String str = input.nextLine();
while (str.length() > 0) {
pw.println(str);
pw.flush();
str = input.nextLine();
}
}
catch (IOException xIo) {
xIo.printStackTrace();
}
System.out.println("Done");
}
}
The above code requires at least Java 7 since it uses try-with-resources. Scanner should be closed, just like PrintWriter should be closed. The try-with-resources ensures that they are closed. Note that if file mytext.txt doesn't exist, creating a new PrintWriter will also create the file and if the file already exists, its contents will be removed and replaced with the text that you enter.
After that the prompt is displayed, i.e. Enter a text here, and the user enters a line of text. Method nextLine() will get all the text entered until the user presses Enter. I read your question again and the program should exit when the user presses Enter without typing any text. When the user does this, str is an empty string, i.e. it has zero length. That means I need to assign a value to str before the while loop, hence the first call to method nextLine() before the while loop.
Inside the while loop I write the value entered by the user to the file mytext.txt and then wait for the user to enter another line of text. If the user presses Enter without typing any text, str will have zero length and the while loop will exit.
Written and tested using JDK 12 on Windows 10 using Eclipse for Java Developers, version 2019-03.
To achieve this, we check is length of input is >0:
import java.io.*;
import java.util.Scanner;
public class lesson {
public static void main(String[] args) throws IOException {
File file = new File("mytext.txt");
if (file.exists() == false) {
file.createNewFile();
}
PrintWriter pw = new PrintWriter(file);
System.out.println("Enter a text here: ");
String str;
Scanner input = new Scanner(System.in);
while ((str = input.nextLine()).length() > 0) {
//str = input.next();
pw.println(str);
}
pw.close();
System.out.println("Done");
}
}

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();
}
}
}

In read and write text file i have to print all the data in the text file but it print only the last line how to get all line write

Read and write the text.
In read and write text file i have to print all the data in the text file but it print only the last line how to get all line write.
Program:
public class fs
{
try
{
BufferReader in = new BufferReader(FileReader(C:/Users/madhan kumar/Desktop/read.txt));
String s;
String[] result=null;
while((s=in.readLine())!=null)
{
result=s.split("\\|");
result = String[4];
String Name = result[0];
String age = result[1];
String Sex = result[2];
String field = result[3];
System.out.println("Name :"+Name+"Age :"+age+"Sex :"+Sex+"Field"+field);
BufferedWriter bw =new BufferedWriter (new FileWriter ("out.txt");
bw.write ("Name :"+Name+"Age :"+age+"Sex :"+Sex+"Field"+field);
Bw.close ();
}}
catch(Exception e)
{
System.out.println(e);
}
}
}
My txt file
malik|23|male|student
nakul|30|male|student
ram|27|male|worker
mak|25|male|student
The answer to your main question is that you only see the last line because you create a new BufferedWriter every time you write out to the .txt, and when you do that it deletes text already on the .txt file. To solve this problem simply declare your BufferedWriter outside of the while loop:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.StringTokenizer;
import java.io.FileReader;
import java.io.FileWriter;
public class fs{
public static void main(String[] args){
StringTokenizer str;
try
{
BufferedReader in = new BufferedReader(new FileReader("C:/Users/madhan kumar/Desktop/read.txt"));
BufferedWriter bw = new BufferedWriter (new FileWriter("out.txt"));
String s;
while((s=in.readLine())!=null){
str = new StringTokenizer(s, "|");
String name = str.nextToken();
String age = str.nextToken();
String sex = str.nextToken();
String field = str.nextToken();
System.out.println("Name: "+name+"\tAge: "+age+"\tSex: "+sex+"\tField: "+field);
bw.write("Name: "+name+"\tAge: "+age+"\tSex: "+sex+"\tField: "+field);
}
bw.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
I made a few small adjustments, largest being that I used StringTokenizer which does pretty much the same thing as your splitting method, but is a little more eloquent.

change password of user account in java using text files?

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.

Categories

Resources