Reputation: 1003
I was just wondering if it is possible to read a .txt file until you find a certain word or reading a certain amount of lines. I'm using the Java Scanner and this is what I tried.
reader = new Scanner(new File(path));
find = (String) wupList.getSelectedItem();
reader.useDelimiter(find);
while(reader.hasNext()){
website = reader.next();
username = reader.next();
password = reader.next();
}
This is just a little program I'm making to get the hand of reading .txt files it's not even gonna be used so I'm not going to encrypt the passwords or anything.
Upvotes: 1
Views: 1831
Reputation: 2404
First of all - modify the while
loop to break
at some point. So, let say once you are done reading all the values break
it. Something like
while(reader.hasNext()){
website = reader.next();
username = reader.next();
password = reader.next();
break;
}
//similarly, you can modify the above code
//if you can read all the inputs in one line
while (reader.hasNextLine()) {
String[] lineArray = reader.nextLine().split("specifyDelimeterHere");
website = lineArray[0];
username = lineArray[1];
password = lineArray[2];
break;
}
Now, Why the NoSuchElementException
.
Honestly, this is a guess. You are most probably getting it because you are not breaking out of the while
and/ or closing
the scanner instance. Here the loop is expecting more input but the resource is getting closed. Use close()
defined in Scanner
class to close reader
after the while
loop.
Let me know in the comments if this helps or not.
Upvotes: 2