displaying data from .txt file [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
need help, i want to display the name of the person who just logged in, here is my login code
public void Masuk(){
try {
String lokasi = "D:/settings.txt";
String username = txtUser.getText();
String password = txtPass.getText();
FileReader fr = new FileReader(lokasi);
BufferedReader br = new BufferedReader(fr);
String line, user, pass;
boolean isLoginSuccess = false;
while ((line = br.readLine()) != null) {
user = line.split(" ")[1].toLowerCase();
pass = line.split(" ")[2].toLowerCase();
if (user.equals(username) && pass.equals(password)) {
isLoginSuccess = true;
this.dispose();
new Main_Menu(this, rootPaneCheckingEnabled).show();
break;
}
}
if (!isLoginSuccess) {
JOptionPane.showMessageDialog(null, "USERNAME/PASSWORD WRONG", "WARNING!!", JOptionPane.WARNING_MESSAGE);
}
fr.close();
}catch(Exception e){
e.printStackTrace();
}
}
the login is in form, i used JDialog to dipslay the name of the person who just logged in(MainMenu), here is my MainMenu code right now
public void Berhasil(){
String data = "D:/Settings.txt";
try {
FileReader fr = new FileReader(data);
BufferedReader br = new BufferedReader(fr);
String line = br.readLine(),nama;
nama = line.split(" ")[0].toLowerCase();
String message = "Selamat datang "+ nama;
String text;
while ((line = br.readLine()) != null)
txtBerhasil.setText(""+message);
}
catch (FileNotFoundException fnfe) {
fnfe.getMessage();
}
catch (IOException ioe) {
ioe.getMessage();
}
}
the .txt file looks like this
Name Username Password
i only want to write the name of the person who just logged in

I'm assuming you want to read some text (the user's information) from a text file. There are several ways to do it. This is one way:
File file = new File("path/to/file.txt");
Scanner sc = new Scanner(file);
String thisLine = null;
while (sc.hasNextLine()){
thisLine = sc.nextLine();
}
Now you can do whatever you want with thisLine. Say you want the first word in the first line:
String[] words = thisLine.split(" ");
System.out.println(words[0]);
This would print the first word in the first line of your txt file. I used space as the separator but it actually depends on what separator you used in yout txt file when you were saving the info. For instance, you may want to use "\t" if tab was used as the separator.

Related

Out of bounds error, while reading file then splitting it [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I've been getting an Array Index Out of Bounds Error.
Basically I have a file where a user name and password is saved lke this: user:password
I'm trying to read the file to check if a new user is already signed in or not. This is in a thread and also using a socket.
private void authentication(String user, String password) {
List<String> nomes = new ArrayList<>();
List<String> pass = new ArrayList<>();
BufferedReader reader;
try {
FileWriter fw = new FileWriter("users.txt", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw);
BufferedReader br = new BufferedReader(new FileReader("users.txt"));
//String line;
String line;
while((line = br.readLine())!=null){
String[] pair = line.split(";");
nomes.add(pair[0]);
pass.add(pair[1]);
}
/*while ((line = br.readLine()) != null) {
String[] info = line.split(":");
System.out.println(line);
System.out.println(info[0]);
System.out.println(info[1]);
}*/
if(nomes.isEmpty()) {
out.println(user + ":" + password);
System.out.println("Novo Utilizador Autenticado.");
System.out.println("Bem Vindo!!");
}else if(nomes.contains(user)) {
bw.newLine();
if(password.equals(pass.get(nomes.indexOf(user)))) {
System.out.println("Utilizador autenticado com sucesso!");
System.out.println("Bem Vindo de Volta!!");
}
}else {
terminate();
}
bw.close();
br.close();
out.close();
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
The error is happening in the last line on the pair[1]. It has a value but for some reason isn't seeing it.
Your text in the file is like "user:password" and you are trying to split it with ";". So pair[1] won't have any value. You should try split it with ":"
Try to access the values dynamically using index instead of hardcoded 0,1 to avoid index out of bond exception :
while ((line = br.readLine()) != null) {
String[] info = line.split(":");
int index = 0;
System.out.println(line);
while(index < info.length){
System.out.println(info[index++]);
}
}

Scanner only searching first line of .txt file

I'm in a beginning programming class, and seem to be having a major issue with searching a text file. What my code should do, based on the assignment:
Accept input, in this case a name and place that input into a .txt file
Allow the user to search for a name, or part of a name, and return all lines with matching text.
I have the input portion of the assignment complete, and am on the verge on completing the retrieval portion, but my code only searches the first line of the .txt file. I am able to print out all lines of the .txt file, and if I search for the name in Line 1 of the .txt file, it will print the line correctly. My issue comes when I am searching for a name that is not on Line 1. Below is my code:
System.out.println ("Would you like to retrieve names from your index? (YES/NO)");
try
{
retrieve=input.readLine();
}
catch (IOException E)
{
System.out.println(E);
}
}
if (choice == 2 && retrieve.equalsIgnoreCase("YES") || retrieve.equalsIgnoreCase("Y"))
{
while (retrieve2.equalsIgnoreCase("YES") || retrieve2.equalsIgnoreCase("Y"))
{
FileReader reader = new FileReader("Name_Index.txt");
BufferedReader bufferedReader = new BufferedReader(reader);
String line = bufferedReader.readLine();
System.out.println ("Enter a string of characters in which to search by or enter \"all names\" f$
search_term = gatherInput();
System.out.println("Search results include: ");
ArrayList<String> list = new ArrayList<String>();
Scanner inFile = new Scanner (new File("Name_Index.txt"));
inFile.useDelimiter(",");
while (inFile.hasNextLine())
{
list.add(inFile.nextLine());
}
Collections.sort(list);
if (search_term.equalsIgnoreCase("all names"))
{
for (String temp : list)
{
System.out.println(temp);
}
}
else if (line.toLowerCase().contains(search_term.toLowerCase()))
{
System.out.println(line);
bufferedReader.close();
}
System.out.println("End!");
System.out.println ("Would you like to retrieve names from your index? (YES/NO)");
try
{
retrieve2=input.readLine();
}
catch (IOException E)
{
System.out.println(E);
}
}
System.out.println("Thank you, come again!");
}
}
public static String gatherInput()
{
Scanner scan = new Scanner(System.in);
String user_input = scan.nextLine();
return user_input;
}
}
I have tried expanding the while (inFile.hasNextLine()) loop to include the second "if" statement, however that creates an issue for the "all names" search - it returns the entire list multiple times (however many lines are in the file). I have even tried creating another while (inFile.hasNextLine()) loop within the second "if" statement, and there is no difference in outcome.
I'm so frustrated at this point, because I've been working on this code for over a week, and have reviewed all of my notes and lecture recordings for this assignment with no help. Any insight would be much appreciated.
You are reading only 1 line of the file
String line = bufferedReader.readLine();
Why don't you read all lines and store them in a List;
List<String> lines = new ArrayList<>();
String line = bufferedReader.readLine();
while(line != null){
lines.add(line);
line = bufferedReader.readLine();
}
bufferedReader.close();
Then to print all lines containing a substring ignorecase:
lines.stream().filter(l -> l.toLowerCase().contains(search_term.toLowerCase))
.forEach(s -> System.out.println(s));
You need to loop the readLine()
For example:
File f = new File(ruta);
if(!f.exists()) //Error
else {
#SuppressWarnings("resource")
BufferedReader br = new BufferedReader(new FileReader(f));
String line;
while ((line = br.readLine()) != null) {
//line = the next line
}
}

Java Error ArrayIndexOutofBounds [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
i got a code that i am implementing from another but i get the error of Java ArrayIndexOutofBoundsException can someone help me? I am not sure of what to do it might be the codes that trigger the error
the data in the file is
Username|HashedPassword|no.of chips
code is below
public static void DeletePlayer()throws IOException{
File inputFile = new File("players.dat");
File tempFile = new File ("temp.dat");
BufferedReader read = new BufferedReader(new FileReader(inputFile));
BufferedWriter write = new BufferedWriter(new FileWriter(tempFile));
ArrayList<String> player = new ArrayList<String>();
try {
String line;
Scanner reader = new Scanner(System.in);
System.out.println("Please Enter Username:");
String UserN = reader.nextLine();
System.out.println("Please Enter Chips to Add:");
String UserCadd = reader.nextLine();
while((line = read.readLine()) != null){
String[] details = line.split("\\|");
String Username = details[0];
String Password = details[1];
String Chips = details[2];
Integer totalChips = (Integer.parseInt(UserCadd) + Integer.parseInt(Chips));
if(Username.equals(UserN)){
line = Username + "|" + Password + "|" + totalChips;
write.write("\r\n"+line);
}
}
read.close();
write.close();
inputFile.delete();
tempFile.renameTo(inputFile);
main(null);
}catch (IOException e){
System.out.println("fail");
}
}
String[] details = line.split("\\|");
String Username = details[0];
String Password = details[1];
String Chips = details[2];
It seems that your details array has only one or two elements. The moment, you try to get something from the array, for an index that is out of (the existing) range, that Exception is thrown.
Are you sure your file doesn't end with an empty line ?
add the line:
System.out.println("length: " + details.length);
right after your split method, or print out all the element of the details array, that will tell you how many elements there are, and how many times you try to do this for which values.
In this code:
while((line = read.readLine()) != null){
String[] details = line.split("\\|");
String Username = details[0];
String Password = details[1];
String Chips = details[2];
//...
}
You must check if the user input is at the expected format, in your case,
joe|g00d|12
The minimal check is to have 3 elements separated by |. e.g.
while((line = read.readLine()) != null){
String[] details = line.split("\\|");
if (details.length != 3) {
System.out.println("Bad input, try agains...");
continue;
}
String Username = details[0];
String Password = details[1];
String Chips = details[2];
//...
}
Note that you should String#trim() your inputs in order to strip leading and ending whitespaces (this allows an input like joe | g00d | 123), and you still can have an error when parsing the number of chips which has to be an integer. I would also certainly check that.

Find all string “ID” in a .txt file [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
How do I find all string "ID" in an existed .txt file and get how many strings were found?
I have a .txt file like:
Product ID = "001", Product Name = "P1"
Product ID = "002", Product Name = "P2"
Product ID = "003", Product Name = "P3"
...
I would like to add Product ID = "LASTEST_ID_PLUS_1, Product Name = "new" at the end of file, but don't know how to get the last ID number.
String filename = "test.txt";
int numOfIds = 0;
try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
String line = null;
while ((line = br.readLine()) != null) {
if (line.contains("Product ID = ")) {
numOfIds++;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Should be a good starting point. Save up the last read ID and then use that for appending.
Edit:
After looking at your question again, I'm not even sure why your .txt file has Product ID =in it. Make the txt file look like this for much easier handling:
001,P1
002,P2
003,P3
unless you didn't show the entire file and there are different things than product IDs stored.
InputStreamReader converter = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(converter);
while(CurLine = in.readLine())
//after exiting the loop
you can use StringBuilder methods "indexOf" and "subString".
then you can catch the last id.
LineNumberReader lnr = null;
try {
File file = new File("productList.txt");
lnr = new LineNumberReader(new FileReader(file));
lnr.skip(Long.MAX_VALUE);
int lineNumber = lnr.getLineNumber();
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file, true)));
String productName = getProductName(); // may be a user input
out.println("Product ID = \""+lineNumber+"\", Product Name = \""+productName+"\"\n");
out.close();
} catch (Exception ex) {
// handle it
} finally {
try {
lnr.close();
} catch (IOException ex) {
Logger.getLogger(H.class.getName()).log(Level.SEVERE, null, ex);
}
}
I've assumed each line contains a product and sequence number start with 1.

How can I read a text file and display it using JoptionPane?

I am trying to take in user input and storing it in a text file, I was able to take in the input and storing it but now i am trying to display that input in a JOptionPane window. Can someone please help me. I am new on stackflow and this is my first post.
/*Here i am taking in user input and storing it in a file called "dictionary.txt".*/
public static String addNewWord()throws IOException
{
String newWord = "";
newWord = JOptionPane.showInputDialog(null, "Enter the word you want to add to your dictionary.");
FileWriter aDictionary = new FileWriter("dictionary.txt", true);
PrintWriter out = new PrintWriter(aDictionary);
out.println(newWord);
out.close();
aDictionary.close();
return newWord;
}
/* Now i am trying to read "dictionary.txt" and display it using JOptionPane*/
public static String listDictionary()throws IOException
{
FileReader aDictionary = new FileReader("dictionary.txt");
String aLineFromFile = FileReader;
JOptionPane.showMessageDialog(null, aLineFromFile);
aDictionary.close();
return aLineFromFile;
}
You should use a BufferedReader to read the data back from the file:
public static void listDictionary()throws IOException
{
BufferedReader br = new BufferedReader(new FileReader("dictionary.txt"));
String aLineFromFile = null;
while ((aLineFromFile = br.readLine()) != null){
JOptionPane.showMessageDialog(null, aLineFromFile);
}
br.close();
return;
}

Categories

Resources