Reputation: 93
it is probably a simple question. I have a problem with scanning a text file. I want to scan a text file and to show the message in a JOptionPane. It scans but it shows only the first line of my text file and then stops disregarding the other lines. If I can get a little help. Thank you very much! Here is my code:
File file = new File("src//mytxt.txt");
try{
Scanner input = new Scanner(file);
while(input.hasNext()){
String line = input.nextLine();
JOptionPane.showMessageDialog(null, line);
return;
}
input.close();
}
catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(null, "File not found");
}
}
Upvotes: 0
Views: 546
Reputation: 1970
Using
while (input.hasNext())
{
//
scan
and append each line to a String
variable
}`
scan
each line from the file and keep the whole text in a String
variable.
Then use JOptionPane.showMessageDialog(null,op)
to show the whole text in a single JOptionPane
.
Upvotes: 0
Reputation: 5629
If you want the whole file to be displayed in a single JOptionPane
, then create a StringBuilder
for it, append every line to it and then show it.
File file = new File("src//mytxt.txt");
try {
Scanner input = new Scanner(file);
StringBuilder op = new StringBuiler();
while (input.hasNext()) {
op.append(input.nextLine());
}
JOptionPane.showMessageDialog(null, op.toString());
input.close();
}
catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(null, "File not found");
}
Upvotes: 5
Reputation: 11173
Now you are displaying only the one line in JOptionPane
. You have to generate the message
before displaying it to JOptionPane
-
File file = new File("src//mytxt.txt");
String message = "";
try{
Scanner input = new Scanner(file);
while(input.hasNext()){
String line = input.nextLine();
message = message+line;
}
JOptionPane.showMessageDialog(null, line);
}
catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(null, "File not found");
}finally{
input.close();
}
}
Upvotes: 0