Problems with reading from a file in java, .txt file always erases - java

I'm taking a Grade 11 course in Java right now, and thus I am new to programming in Java. My assignment is to ask the user their name and a password, put their password on a .txt (the .txt file's name would be the name they input), and ask if they've played before (that's for the second half of the assignment). If they enter 'no' it will ask them to input a password for the future. If they exit and run the program again and input 'yes' then it will prompt the user to input the password they put in when they said 'no'.
Here's the code:
import java.io.*;
class passwordtest
{
public static void main (String args[])
throws java.io.IOException
{
BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
String name, password, input, filepassword;
System.out.println ("Please enter your name");
name = br.readLine ();
FileWriter fw = new FileWriter (name + ".txt");
System.out.println ("Have you played this game before?");
input = br.readLine ();
if (input.equalsIgnoreCase ("no"))
{
System.out.println ("Please enter a password that you can use for later.");
password = br.readLine ();
fw.write (password);
fw.close ();
}
if (input.equalsIgnoreCase ("yes"))
{
FileReader fr = new FileReader (name + ".txt");
BufferedReader bfr = new BufferedReader (fr);
filepassword = bfr.readLine ();
System.out.println ("Please enter your password");
password = br.readLine ();
if (!password.equals (filepassword))
{
System.out.println ("Wrong password.");
}
if (password.equals (filepassword))
{
System.out.println ("Right password. Enjoy the program!");
}
}
}
}
The problem here is that every time I run the program to say 'yes' the .txt file erases, thus making it impossible for me to be able to see if the user entered the correct password.
I've been struggling with this for the past couple of hours, please help.

FileWriter fw = new FileWriter (name + ".txt");
This is enough to create a new file. Place it carefully.

Related

How can I compare an integer and a file name?

I am trying to make a login/password program which asks if you have an account and you can also make one.
By account I mean the program will give you a random 8 digit number.
I also have a FileWriter which creates a file based on the ID you were given. And I have a FileReader which will eventually read what you previously exported to your file so you can update it.
The problem I have is that when I ask the user if they have an account already, if they say yes it will ask the user for their UserID.
My plan was that when it read your UserID it would scan the folder I have my .java file saved in and look for a .txt file with the same name as your UserID. For example, if you make an account and the UserID it gives you is 12345678 it will create a file named 12345678 and then when you input you UserID it will scan to see if that file exists.
Currently The problem that occurs is the it prints
Error File Not Found(the catch String I wrote)
even though I have that file in the folder.
I think there is something wrong with how I am comparing to see if the UserID matches any file name.
The "Login" class.
import java.awt.*;
import hsa.Console;
import java.util.Random;
import java.io.*;
import java.io.File;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.FileNotFoundException;
public class Login
{
static Console c;
static Login player1;
public static void main (String[] args)
{
player1 = new Login ();
player1.FileReaderTest (25756326);
//player1.Userlogin (); //I think it has something to do with this
} // main method
public void Userlogin (File input)
{
c = new Console ();
Random rand = new Random ();
c.println ("Hello do you have an account?");
String Q1 = c.readLine ();
Q1 = Q1.toUpperCase ();
if (Q1.equals ("YES"))
{
c.println ("Please input your User ID");
int login = c.readInt ();
if (String.valueOf(login).equals (input))//I think it has something to do with this
{
try
{
FileReader reader = new FileReader (input);
BufferedReader buf = new BufferedReader (reader);
String line1 = buf.readLine ();
String line2 = buf.readLine ();
buf.close ();
c.println (line1);
c.println (line2);
}
catch (FileNotFoundException e)
{
c.println ("Error File Not Found");
}
catch (Exception e)
{
c.println ("ERROR");
}
}
}
else if (Q1.equals ("NO"))
{
c.println ("Please enter your name ");
String name = c.readLine ();
int UserID = rand.nextInt (99999999);
c.println ("Your User ID is " + UserID);
player1.FileCreation (UserID);
player1.FileReaderTest (UserID);
}
while (!Q1.equals ("YES") && !Q1.equals ("NO")) //While Q1 != YES || NO
{
c.println ("Please Answer the question with Yes or No");
c.println ("Hello do you have an account?");
String Q2 = c.readLine ();
Q2 = Q2.toUpperCase ();
if (Q2.equals ("YES"))
{
c.println ("Ok lets start");
break;
}
else if (Q2.equals ("NO"))
{
c.println ("Please enter your name ");
String name = c.readLine ();
int UserID = rand.nextInt (89999999) + 10000000;
c.println ("Your User ID is " + UserID);
player1.FileCreation (UserID);
player1.FileReaderTest (UserID);
break;
}
} //While Q1 != YES || NO
} //Public void Main
public void FileReaderTest (int UserID)
{
File input = new File (String.valueOf (UserID));
player1.Userlogin (input);
try
{
FileReader reader = new FileReader (input);
BufferedReader buf = new BufferedReader (reader);
String line1 = buf.readLine ();
String line2 = buf.readLine ();
buf.close ();
c.println (line1);
c.println (line2);
}
catch (FileNotFoundException e)
{
c.println ("Error File Not Found");
}
catch (Exception e)
{
c.println ("ERROR");
}
}
public void FileCreation (int UserID)
{
try
{
Writer writer = new BufferedWriter (new OutputStreamWriter (new FileOutputStream (String.valueOf (UserID)), "utf-8"));
}
catch (IOException ex)
{
}
}
} // Login class
So, you have a File input, and you want to compare the name of the file, so you instead want
String.valueOf(login).equals (input.getName());
If you are getting an error on
File input = new File (String.valueOf (UserID));
then note: "2.txt", for example, is very different than a file named just "2" (which is worth mentioning because Windows hides file extensions by default)
And if you aren't giving the full path to the file, then that file has to be in your "classpath", which if you don't understand, better to give the full path to the file.
FileNotFound is not thrown after a comparison but by your FileReader when it is created. FileReader tells you that there is not file named as such. Since you said that you did create the file, there can be a few explanations:
Maybe the file you created is in the wrong folder. The default folder for a java program is the project folder. Make sure that you have your file in the right folder. Else you can give the full path as an argument for the FileReader: "/my/full/path/filename.extension".
It can also be a problem of extension. If you are using a Windows OS, the extension may be hidden in the file explorer. Right clic on your file and check whether there is such an extension (ex: ".txt")
Eventually you can open the file with a FileWriter under Java, and try to create the file within your program. You will see more easily which file Java is trying to access and it will help you identify your issue.
Since you have mentioned that you need to create the text file associated with the UserId, I would suggest adding the ".txt" in the FileReaderTest class. Something similar to this :
File input = new File (String.valueOf (UserID)+".txt");
Or more conveniently
File input = new File (Integer.toString(UserID)+".txt");
I think this solves your query.

File Reader and implementing it into a Cipher

I am pretty new to Java, kind of getting the hang of it, and am working on some code for a Caesar Cipher in my CS class. I have it able to read one line of code from a file and it can decrypt and encrypt just fine, but I think my teacher wants a full document to be able to be encrypted or decrypted. I know it's possible to have it read the entire document and store it into a string, but how would I go about doing that?
Thanks for any help! Let me know if you need to see my other Class, if you need it for reference.
import java.util.Scanner;
import java.io.*;
public class Project3 {
public static void main(String[] args) {
Cipher caesar = new Cipher();
Scanner input = new Scanner(System.in);
System.out.println("Please enter a filename to encode or decode.");
String f = input.nextLine();
String fileName = f;
String line = null;
System.out.println("Enter the number of steps to encode or decode the file by: ");
int i = input.nextInt();
input.nextLine();
try {
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null){
System.out.println(line);
System.out.println("What would you like to do? Enter [e] to encrypt or press [d] to decrypt.");
String a = input.nextLine();
if(a.equals("e")){
String encoded = caesar.useCipher(line,i);
caesar.writeToFile(encoded);
break;
}
if(a.equals("d")){
String decoded = caesar.useCipher(line,(-i));
caesar.writeToFile(decoded);
break;
}
}
}
catch(FileNotFoundException ex){
System.out.println("Unable to open file '" + fileName + "'");
}
catch(IOException ex){
System.out.println("Error reading file '" + fileName + "'");
}
}
}
Your code already has the loop to process the entire file.
The only problem is the prompt asking what the user wants to do. THAT part belongs outside (before) the while loop.

Reading null values from BufferedReader in command prompt input

I'm trying to read from the user's input from command line. For the input for filename, the program is supposed to exit whenever it detects that the user has submitted a blank value.
However, the program is always going to the "Inside Reading file" code, regardless of whether the user input contains anything or not. It never gets to execute the "Program will exit now" code. I've tried different ways of coding it, and all of them came back with the same results. Is there anything wrong with it?
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String collection;
String filename;
System.out.println("Enter the collection name: ");
collection = br.readLine();
String urlString = "http://localhost:8983/solr/" + collection;
solr = new HttpSolrClient(urlString);
doc1 = new SolrInputDocument ();
while (true){
System.out.println("Enter the file name: ");
while ((filename = br.readLine()) !=null) {
System.out.println("Inside reading file ");
parseUsingStringTokenizer(filename);
System.out.println("Enter the file name: ");
}
System.out.println("Program will exit now...");
System.exit(0);
}
}
add one extra condition filename.trim().length()>0 with (filename = br.readLine()) !=null. As != null will not check for whitespaces. And why you have put while(true). It is useless as per your current code.
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String collection;
String filename;
System.out.println("Enter the collection name: ");
collection = br.readLine();
String urlString = "http://localhost:8983/solr/" + collection;
solr = new HttpSolrClient(urlString);
doc1 = new SolrInputDocument ();
System.out.println("Enter the file name: ");
while ((filename = br.readLine()) !=null && filename.trim().length()>0){
System.out.println("Inside reading file ");
parseUsingStringTokenizer(filename);
System.out.println("Enter the file name: ");
}
System.out.println("Program will exit now...");
}
BufferedReader returns null when the end of stream is reached. It returns "" (the empty string of length 0) when the user enters a blank line.
Thus, you should change your loop condition to this:
while (!(filename = br.readLine()).equals(""))

How do I add data to text file and not overwrite what I have in Java

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.");
It is advised to use chain of BufferedWriter and FileWriter, and the key point is FileWriter will append String to current file when use the one of its constructor that lets appaneding by adding true to last paramter like
new FileWriter("login.txt", true)
and 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 file
Note :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 once
Just change your
PrintWriter out = new PrintWriter("login.txt");
to
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("login.txt", true)));
Example:
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("login.txt", true)));) {
String data = "This content will append to the end of the file";
File file = new File("login.txt");
out.println(data);
} catch(IOException e) {
}
It is possible to solve this issue without using BufferedWriter, yet the performance will be low as I mentioned.
Example:
try (PrintWriter out = new PrintWriter(new FileWriter("login.txt", true));) {
String data = "This content will append to the end of the file";
File file = new File("login.txt");
out.println(data);
} catch (IOException e) {
}
Use FileWriter
FileWriter fw = new FileWriter(filename,true);
//the true will append the new data to the existing data
Something like this
PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter("login.txt", true)))
out.println(n);
out.println(p);
out.close();
Very simple example is this.
String workingDir = System.getProperty("user.dir");
System.out.println("Current working directory : " + workingDir);
File file = new File(workingDir+"/WebContent/Files/login.txt");
PrintWriter printWriter = new PrintWriter(new BufferedWriter(new FileWriter(file,true)));
printWriter.println(workingDir);
printWriter.println("Good thing");
printWriter.close();
hope it helps.

FileNotFoundException occurs due to my outputStream method

Please bear with me here as I'm new to the site.
below is a program that I've written for my programming in Java class, and while most of it has gone well so far, I can't seem to get rid of a specific bug.
When the program reaches the third if block (choice == 3) it doesn't let the user enter any data, and if the line
"outputStream = openOutputTextFile(newerFileName);"
is present in the if block then a FileNotFoundException occurs. After tinkering around with my code for a while I've found that the error is being thrown because the program cannot find the inputStream anymore. Although I've checked and have found that the program can still find, read, and write to the file that is throwing the error.
I'm thinking that since the error only occurs when I put the outputStream in, and is being thrown by the inputStream, then it probably has something to do with file streams. I just don't know what exactly
Does anyone have any ideas on how I could solve this issue?
public class FileProgram {
public static PrintWriter openOutputTextFile(String fileName)
throws FileNotFoundException {
PrintWriter toFile = new PrintWriter(fileName);
return toFile;
}
public static Scanner readFile(String fileName)
throws FileNotFoundException {
Scanner inputStream = new Scanner(new File(fileName));
return inputStream;
}
public static void main(String args[]) throws FileNotFoundException {
ArrayList<String>fileReader = new ArrayList<String>(10);
PrintWriter outputStream = null;
Scanner inputStream = null;
Scanner keyboard = new Scanner(System.in);
try {
System.out.println("Enter the name of the text file you want to copy.");
String oldFileName = keyboard.nextLine();
inputStream = readFile(oldFileName);
while(inputStream.hasNextLine()) {
String currentLine = inputStream.nextLine();
fileReader.add(currentLine);
}
System.out.println("All data has been collected. Enter the name for the new text file");
String newFileName = keyboard.nextLine();
outputStream = openOutputTextFile(newFileName);
File userFile = new File(newFileName);
if(userFile.exists())
{
System.out.println("The name you entered matches a file that already exists.");
System.out.println("Here are your options to fix this issue.");
System.out.println("Option 1: Shut down the program.");
System.out.println("Option 2: Overwrite the old file with the new empty one.");
System.out.println("Option 3: Enter a different name for the new file.");
System.out.println("Enter the number for the option that you want.");
int choice = keyboard.nextInt();
if(choice == 1) {
System.exit(0);
} else if(choice == 2) {
outputStream = new PrintWriter(newFileName);
} **else if(choice == 3) {
System.out.println("Enter a different name.");
String newerFileName = keyboard.nextLine();
outputStream = openOutputTextFile(newerFileName);
}**
}
for(int i = 0; i < fileReader.size(); i++) {
String currentLine = fileReader.get(i);
outputStream.println(currentLine);
//System.out.println(currentLine);
}
System.out.println("The old file has been copied line-by-line to the new file.");
}
catch(FileNotFoundException e) {
System.out.println("File not found");
System.out.println("Shutting program down.");
System.exit(0);
}
finally {
outputStream.close();
inputStream.close();
}
}
}
You are having trouble getting a line of input from your Scanner object after calling .nextInt(). In response to the numeric choice, the user enters an integer followed by a newline.
This line reads the integer from the input buffer:
int choice = keyboard.nextInt();
However, there's still a newline in the input buffer right after the number. Thus when you call .nextLine():
String oldFileName = keyboard.nextLine();
You get an empty line. You cannot create a file with an empty string for a file name, so a FileNotFoundException is thrown (this is per spec, see the other answer).
One solution is to consistently use .nextLine(), getting a line at a time from the input buffer. When you need an integer, simply parse the string manually:
int choice = Integer.parseInt( keyboard.nextLine() );
By the way, in debugging this sort of issue it's very useful to get into the habit of adding some printout statements to see what's going on:
public static PrintWriter openOutputTextFile(String fileName)
throws FileNotFoundException {
System.out.println( "Trying to create file: '" + fileName + "'" );
PrintWriter toFile = new PrintWriter(fileName);
return toFile;
}
There are more advanced debugging techniques, but this one is extremely simple, and using it is a lot more effective than using nothing at all.

Categories