I'm making some really simple program in java just to see how I/O works, but I have a problem. I've created"test.txt" file, and now I'm trying to (over Scanner) enter username and password every time when I start program, which is not big deal. I made my program read content from file and write to console. But, my problem is, I want that every time I run program and enter new username that my program go through the file, read every username and give me a warning if username already exist.
Asked
Active
Viewed 1.1k times
0
-
5Possible duplicate of [Java: How to read a text file](http://stackoverflow.com/questions/2788080/java-how-to-read-a-text-file) – byxor Jan 09 '17 at 15:57
-
Please take the [Tour](http://stackoverflow.com/tour) and read the documentation in the [Help Center](http://stackoverflow.com/help). In particular, you should read about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and what sorts of questions are [on topic](http://stackoverflow.com/help/on-topic) here at SO. – azurefrog Jan 09 '17 at 15:57
-
Specifically, if you're asking with help with your code, you need to include that code in your question along with the inputs, expected vs actual outputs, any errors, etc. Ideally include a [mcve]. – azurefrog Jan 09 '17 at 15:58
1 Answers
0
Not sure if this is what you're looking for but this should do the job. It's a quick simple solution.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
String filePath = "{YOUR_FILEPATH_TO_TEST.TXT}";
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your username: ");
String username = scanner.nextLine();
System.out.println("Checking to see if username exists...");
BufferedReader bufferedReader;
try {
bufferedReader = new BufferedReader(new FileReader(filePath));
String line;
boolean usernameExists = false;
while((line = bufferedReader.readLine()) != null) {
if (line.equals(username)) {
usernameExists = true;
break;
}
}
if (usernameExists) {
System.out.println("Username exists! Please try again.");
} else {
System.out.println("Username accepted");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

ubiquitous23
- 32
- 5