I'm trying to read a txt file using Java. I wanted to separate the contents.
Example the content of the txt file is:
[t]
Harry Potter
[a]
J.K Rowling
[c]
Once Upon a time
there was a wizard name Harry Potter
The End.
I want to put the texts with [c]
in a textfield named txtContent
but what happens now is that only the first line is passed in the txtContent
private void btnRetireveActionPerformed(java.awt.event.ActionEvent evt) {
String filename=txtFilename.getText()+".txt";
int x=1;
String text=null;
try (BufferedReader fw = new BufferedReader(new FileReader(new File(filename))))
{
String s;
while((s = fw.readLine()) != null)
{
if(s.equals("[a]"))
{
String author = fw.readLine(); //read the next line after [a]
txtAuthor.setText(author);
break;
}
}
while((s = fw.readLine()) != null)
{
if(s.equals("[c]"))
{
String content = fw.readLine(); //read the next line after [a]
txtContent.setText(content);
break;
}
}
} catch (IOException exp)
{
exp.printStackTrace();
}
}
When you detect if you are currently at [a]
line then you can then read the nextLine
and break the loop.
Use BufferedReader
instead of FileReader
sample:
try (BufferedReader fw = new BufferedReader(new FileReader(new File("text.txt"))))
{
String s;
while((s = fw.readLine()) != null)
{
if(s.equals("[a]"))
{
String author = fw.readLine(); //read the next line after [a]
System.out.println(author); //the line after [a]
}
if(s.equals("[c]"))
{
StringBuilder content = new StringBuilder();
while((s = fw.readLine()) != null)
content.append(s + " ");
System.out.println(content); //the line after [c]
}
}
} catch (IOException exp)
{
exp.printStackTrace();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.