problem in reading text file - java

I have a text file where i have names and passwords separated by :.
user1:pwd1
user2:pwd2
In the login page if the user gives the correct username and password it will lead you to the welcome page. But I am not getting this properly. The output which i get is
user1
pwd1
inside try
user1
pwd1
true
welcome user1
user2
pwd2
false
not equal
My code is below.
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.regex.*;
import com.sun.org.apache.xalan.internal.xsltc.compiler.Pattern;
public class TextFile {
/**
* #param args
*/
public void getNamePwd(String name, String pwd) {
// TODO Auto-generated method stub
System.out.println(name);
System.out.println(pwd);
String[] splitVals=null;
try{
System.out.println("inside try");
String strLine;
BufferedReader br = new BufferedReader(new FileReader("D:\\test\\text.txt"));
while((strLine=br.readLine())!=null){
splitVals=strLine.split(":");
for(int i=0;i<splitVals.length;i=i+2){
System.out.println(splitVals[i].toString());
System.out.println(splitVals[i].toString());
String nameUser=splitVals[i].toString();
String passWord=splitVals[i+1].toString();
System.out.println(name.equals(nameUser));
if((name.equals(nameUser))&&(pwd.equals(passWord))){
System.out.println("welcome"+name);
}
else{
System.out.println("not equal");
}
}
}
}catch(Exception e){
}
}
}
please help me..

I suspect that you want to stop looking for username/password matches after you've found one... To do this you have to break the loop upon a match. To do this you do the following:
readLoop:
while((strLine=br.readLine())!=null){
// ...
String[] splitVals = strLine.split(":");
if((name.equals(nameUser))&&(pwd.equals(passWord))){
System.out.println("welcome"+name);
break readLoop;
}
// ...
}
Besides, I don't know why you need this loop:
for(int i=0;i<splitVals.length;i=i+2)
Recall that you read the file line by line. That is, the splitted array will contain the username and password of the current line.
To print the username / password you could do something like this:
System.out.printf("Username: %s, Password: %s%n", splitVals[0], splitVals[1]);
I would probably solve it using a Scanner. Something like this:
import java.io.*;
import java.util.Scanner;
public class TextFile {
public static void main(String[] args) throws FileNotFoundException {
if (userPassOk("hello", "world"))
System.out.println("Welcome");
else
System.out.println("Get out!");
}
private static boolean userPassOk(String user, String pass)
throws FileNotFoundException {
Scanner s = new Scanner(new File("test.txt"));
while (s.hasNextLine()) {
String[] userPass = s.nextLine().split(":");
if (userPass[0].equals(user) && userPass[1].equals(pass))
return true;
}
return false;
}
}

Try resetting the value of nameUser and passWord at the end of the try()
as in
nameUser="";
passWord="";

Your print statements are wrong. That's why you can't debug this properly.
What you are printing does not match what you are using for the name and password. Fix this and try printing it out again.
for(int i=0;i<splitVals.length;i=i+2){
System.out.println(splitVals[i].toString());
System.out.println(splitVals[i].toString());
String nameUser=splitVals[i].toString();
String passWord=splitVals[i+1].toString();
However, you don't need this loop. You can just use:
String nameUser=splitVals[0];
String passWord=splitVals[1];

put break if your condition is satisfied.Don't allowed continue the loop.If you put the brak here.you got your expected output.
if((name.equals(nameUser))&&(pwd.equals(passWord))){
System.out.println("welcome"+name);
break;
}

Related

How do I add text from a string to a pre-existing txt file?

I am writing a Java program that is a password authenticator. The user enters a password and then is asked to confirm the password by re-entering it. If the second password matches the first the password will be confirmed and set to the password variable. But if the passwords don't match then the second password entered should be recorded and logged in a pre-existing txt file. As well as this the loop will start again and the user will be asked to re-enter their passwords and confirm them.
I have tried creating a file and then writing to it in the else if condition, however then that means the each time the user enters a wrong password the txt file is created again and only the last entered password is recorded instead of the entire list of wrong passwords that were entered.
Here is my code below.
package passwordAuthenticator.java;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import java.util.Formatter;
public class passwordAuthenticator {
public static void main(String[] args) {
// TODO Auto-generated method stub
String password;
try {
File myObj = new File("Passwords.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
while(true){
System.out.println("Please enter password: ");
Scanner sc = new Scanner(System.in);
String firstPassword = sc.nextLine();
System.out.println("Please confirm password: ");
Scanner sc1 = new Scanner(System.in);
String secondPassword = sc.nextLine();
if(firstPassword.equals(secondPassword)) {
System.out.println("Password confirmed.");
password = secondPassword;
break;
} else if(firstPassword != secondPassword) {
try {
FileWriter myWriter = new FileWriter("Passwords.txt");
myWriter.write(secondPassword);
myWriter.close();
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
System.out.println("\nPasswords are not a match. Retry!\n");
}
}
}
}
Thank you for your time looking at this with me.
Your programs works well. The only change is this.
You should use this constructor. Just add true as the last parameter
FileWriter myWriter = new FileWriter("Passwords.txt", true);
Here's the description
/**
* Constructs a FileWriter object given a file name with a boolean
* indicating whether or not to append the data written.
*
* #param fileName String The system-dependent filename.
* #param append boolean if <code>true</code>, then data will be written
* to the end of the file rather than the beginning.
* #throws IOException if the named file exists but is a directory rather
* than a regular file, does not exist but cannot be
* created, or cannot be opened for any other reason
*/
public FileWriter(String fileName, boolean append) throws IOException {
super(new FileOutputStream(fileName, append));
}
public FileWriter(String fileName, boolean append) should work for you.

java - read user input and print line if it is a duplicate

So I'm learning about reading text files in java and I'm trying to write a program that reads user input one line at a time and outputs the current line if and only if it is a duplicate of some previous line. This is the part of code I'm struggling with and was wondering if I could get a push in the right direction. Right now it currently asks for user input, and when I write a line and press enter, the program ends without printing anything.
public static void doIt(BufferedReader r, PrintWriter w) throws IOException {
Set<String> s = new HashSet<String>();
while(true) {
String line = r.readLine();
if(s.contains(line)) {
s.add(line);
}else {
break;
}
}
for (String text : s) {
w.println(text);
}
}
You can keep two mutable states, one for all the lines and one for duplicate lines.
Example below. (You can exit program on :q).
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;
public class CheckDupes {
public static void main(String[] args) throws IOException {
Set<String> lines = new HashSet<String>();
Set<String> duplicateLines = new HashSet<String>();
BufferedReader stdReader =
new BufferedReader(new InputStreamReader(System.in));
String line = null;
while (!(line = stdReader.readLine()).equals(":q")) {
if (lines.contains(line)) {
duplicateLines.add(line);
} else {
lines.add(line);
}
}
duplicateLines.forEach(l -> System.out.println(l));
}
}
Input/ Output
love is great
weather is good
software is version 4
weather is good
love is great
:q
weather is good
love is great

Java URL method not filling properly with recursion

import java.util.Scanner;
import java.net.MalformedURLException;
import java.net.URL;
import java.io.IOException;
public class Main {
// takes user input and validates
public static URL URLPrompt() throws MalformedURLException {
URL pageLocation = null;
Scanner in = new Scanner(System.in);
System.out.println("Please enter a webpage URL to find all it's links: ");
try {
pageLocation = new URL(in.nextLine());
} catch (MalformedURLException exception) {
System.out.println("Invalid URL");
URLPrompt();
}
return pageLocation;
}
public static void main(String[] args) throws MalformedURLException, IOException {
Scanner in = new Scanner(System.in);
URL pageLocation = URLPrompt();
Scanner scan = new Scanner(pageLocation.openStream());
while (scan.hasNext()) {
String webFile = scan.nextLine();
// Searches for all hyperlinks in <a href=> </a> form
if (webFile.contains("<a href=") && webFile.contains("</a>")) {
int x = webFile.indexOf("<a href=");
int y = webFile.indexOf("</a>");
String link = webFile.substring(x, y + 4);
System.out.printf("%s\n", link);
}
}
scan.close();
in.close();
}
}
So this program is supposed to take a user inputted url link and print out all of the hyperlinks in html form, "a href" to the closing "a" tag. This code does just that if the url is valid initially. However, if an invalid url is input the system catches it and the Urlprompt method calls itself, when the method calls itself after an invalid input and then a valid URL is input during recursion I get a nullpointer exception on line 24... How can I get the URLPrompt method to accurately fill the variable pageLocation during recursion?
The recursive call should be return URLPrompt().
BTW: I wouldn't use recursion for this purpose (it's just a waste of stack frames), just a simple while loop.

How do I accept a command and a filename in the same input string in java?

Basically this is what my input will look like:
C:> ltf sample.txt
Then Shell v2.0(program) creates a sample.txt file in C drive.
I have explored the split() function but I have to validate my input from the commands stored in my array. So I need to "store" the file name in my array as well. I know this isn't plausible as the file names would vary. Basically what I am trying to ask is, how do I accept a command and a file name together? This is my current code just to give you an idea of what I am trying to do
package assignment311;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.util.*;
import javax.swing.JOptionPane;
public class assignment {
/*Data Members*/
public static String[] myData;
public static String CurrentPath;
/*Methods*/
public assignment()
{
myData=new String[13];
myData[0]="ls";
myData[1]="ls -la";
myData[2]="less";
myData[3]="gd";
myData[4]="md";
myData[5]="rnd";
myData[6]="del";
myData[7]="hd";
myData[8]="uhd";
myData[9]="ltf";
myData[10]="nbc";
myData[11]="gdb ";
myData[12]="Tedit";
//initialise currentpath
CurrentPath="C:/";
}
public static void main(String[] args)
{
//initialise data by constructing an object of class
assignment obj=new assignment();
String userInput="";
do
{
//while
//get user input
System.out.print(" "+CurrentPath+"> ");
Scanner scan=new Scanner(System.in);
userInput=scan.nextLine();
String[] stringarray = userInput.split(" ");
/// boolean variable to display information about command validity
boolean isFound=false;
for(int j=0;j<myData.length;j++)
{
if(userInput.equals(myData[j]))
{
isFound=true;
if(stringarray[0].equals("ls"))
{
obj.Run_Ls();
}
if(stringarray[0].equals("gd"))
{
//ask user to enter a folder name
System.out.println("enter a valid folder name");
//get input
String fdname=scan.nextLine();
//get all folders name
File myfile=new File(CurrentPath);
String[] allfiles=myfile.list();
// match user input with folder names
boolean isdirthere=false;
for(int k=0;k<allfiles.length;k++)
{
if(fdname.equals(allfiles[k]))
{
CurrentPath=CurrentPath+"/"+allfiles[k];
isdirthere=true;
}
}
if(!isdirthere)
{
System.out.println("Invalid Folder Name");
}
}
if(userInput.equals("ltf"))
{
System.out.println("Enter valid file name");
String filename=scan.nextLine();
final Formatter x;
try
{
x = new Formatter(filename);
System.out.println("File Created");
}
catch (Exception e)
{
System.out.println("Error man");
}
}
if(userInput.equals("nbc"))
{
}
}
}
if(!isFound)
{
System.out.println("Invalid Command");
}
// scan.close();
//end of while
}
while(!userInput.equals("exit"));
}
public void Run_Ls()
{
File obj=new File(CurrentPath);
String[] ls_result=obj.list();
for(int i=0;i<ls_result.length;i++)
{
System.out.println(ls_result[i]);
}
}
}
Instead of storing simple strings, store lists or arrays of strings:
String[][] myData = {
{"ls"},
{"ls", "-la"}
};
This way, you can preserve the structure of your commands (i.e. command name and all the arguments) without having to make guesses what a space in there might mean.
You need command and filename on the same line. Instead of checking for userInput.equals, you could try using userInput.startsWith, this will return true when your input starts with a command which matches the array myData.
You may run into issues where there are two command which have the same starting alphabets like:
myData[0]="ls";
myData[1]="ls -la";
You could change the above to:
myData[0]="ls -la";
myData[1]="ls ";
After you find a command which matches your list, you can do a substring where
String fileName = userInput.subString(myData[x].length).trim();
For a string "cmd ", the above operation will return only .
this will give you the flexibility of not worrying about the different file formats.
You may need to add some validation to the fileName variable though.

Java How To Read A Specific Line

I want help myself, I made a file that would create a user file, because I plan on making a game. It has a login that writes the Login name, the Display name, and the Password. It writes it out to a file named after the Login Name.
Now I wish to make a login script as well, using java. I want to know, specifically, how to read the line and the already entered password.
I have it so that when it creates the file, it saves the password twice, once as "playerPass" and once as "currPass" so that, if one planned to change the password (which I will use from the login script), then the currPass would be read as the correct password using the playerPass variable. Anyway, I would like for it to use BufferedReader and FileReader to read the line indicating the password and the current password so that one may log in.
Can someone help me out a lot with this? I am still, to a point, novice.
PS. I can tweak code, I just need a little explanation on HOW TO code it lol.
Variables:
playerLogName
playerName
playerPass
currPass
File names:
Login.java
CharacterFileCreator.java
MADE AN ADDITION, got it half working, but it locks up (using Dr. Java) after I enter password, regardless of what I do, incorrect or correct, and the System.out.println() never executes, even if the password is incorrect. Check it:
import java.util.Scanner;
import java.io.BufferedWriter;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.IOException;
import java.io.FileNotFoundException;
class Login {
public static void LogIn(){
boolean loggedIn = false;
loggedIn = true;
System.out.println("You are now logged in!");
}
public static void main(String[] args) {
System.out.println("What is your login name?");
Scanner charLogName = new Scanner(System.in);
String playerLogName = charLogName.nextLine();
boolean charFileFound = false;
BufferedReader characterfile = null;
try {
characterfile = new BufferedReader(new FileReader("./game/characters/" + playerLogName + ".txt"));
charFileFound = true;
}
catch (FileNotFoundException fileex1) {}
if(charFileFound == false){
System.out.println("Login name does not exist!");
}
else
{
System.out.println(playerLogName + ": is your username, what is your password?");
Scanner charPassword = new Scanner(System.in);
String playerPass = charPassword.nextLine();
String line = "";
String token = "";
String token2 = "";
int ReadMode = 0;
try {
line = characterfile.readLine();
} catch (IOException ioexception) {
System.out.println(playerLogName + ": error loading file.");
}
while (line != null) {
line = line.trim();
int spot = line.indexOf("=");
if (spot > -1) {
token = line.substring(0, spot);
token = token.trim();
token2 = line.substring(spot + 1);
token2 = token2.trim();
switch (ReadMode) {
case 1:
if (token.equals("character-password")) {
if (playerPass.equals(token2)) {
LogIn();
} else {
System.out.println("You entered an incorrect password!");
}
break;
}
}
} else {
if(line.equals("[ACCOUNT]")) {
ReadMode = 1;
}
else if(line.equals("[EOF]")) {
try {
characterfile.close();
} catch (IOException ioexception) {
}
}
}
}
}
}
}
EDIT:
SAMPLE FILE:
[ACCOUNT]
character-loginname = SampleFile
character-password = samplepassword
[EOF]
It would probably be easier to use a properties file! You can still give it any file extension you want and even encrypt it if you so wish, but by using the Properties object you can get or set any property regardless of the line number!
Look here for an example: http://www.exampledepot.com/egs/java.util/Props.html
UPDATE: I have spotted your problem - you are never reading the next line of the file in your while loop, so you would probably find that if you put System.out.println(line); somewhere inside of the loop it would just keep displaying "[ACCOUNT]" - the first line of your file!
To solve this problem, I may be inclined to put the entire loop in a try catch statement and change the condition to while((line = characterfile.readLine()) != null). That way, every loop uses the next line, but it could be problematic in terms of catching exceptions, depending on the situation.
Alternatively, you could add line = characterfile.readLine(); after you set ReadMode to 1 in your if(line.equals("[ACCOUNT]")) statement, and as an else statement when testing if (token.equals("character-password"))....
However, if you do follow my advice and use the Properties file you will not be required to do any looping to get the character data as you can just call something like password = propertyObject.getyProperty("password") as the example link shows.
HTH

Categories