This is my code so far but it overwrites what I have in the text file already. What I want is for it to add it to a new line in the text file.
import java.io.*;
import java.util.Scanner;
public class Login{
public static void main(String[] args) throws IOException {
Scanner s1,s2;
s1 = new Scanner(new FileInputStream("login.txt"));
s2 = new Scanner(System.in);
boolean loggedIn = false;
String name,pword,n,p;
System.out.println("Are you a new user? (Type y for yes or n for no)");
String nU = s2.next();
if (nU.equals("n"))
{
System.out.println("Enter username:");
n=s2.next();
System.out.println("Enter password:");
p=s2.next();
while(s1.hasNext()){
name=s1.next();
pword=s1.next();
if(n.equals(name) && p.equals(pword)){
System.out.println("You are logged in.");
loggedIn = true;
break;
}
}
if(!loggedIn)
System.out.println("Incorrect password or username.");
}
else if (nU.equals("y"))
{
Down here is where the problem with my code will be as this is where it is writing it to the file.
PrintWriter out = new PrintWriter("login.txt");
System.out.println("Enter username:");
n=s2.next();
System.out.println("Enter password:");
p=s2.next();
out.append(n);
out.append(p);
out.close();
System.out.println("Account has been created and you are logged in.");
}
else
System.out.println("Invalid response.");
Very simple example is this.
hope it helps.
It is advised to use chain of
BufferedWriter
andFileWriter
, and the key point isFileWriter
will append String to current file when use the one of its constructor that lets appaneding by addingtrue
to last paramter likeand when we surrounding it with
BufferedWriter
object in order to be more efficient if you are going to write in the file number of time, so it buffers the string in big chunk and write the big chunk into a file and clearly you can save a lot of time for writing into a fileNote :It is possible not to use
BuffredWriter
,but it is advised because of better performance and ability to buffer the big chunk of Strings and write them onceJust change your
to
Example:
It is possible to solve this issue without using
BufferedWriter
, yet the performance will be low as I mentioned.Example:
Use FileWriter
Something like this