gpt4 book ai didi

Java Swing 将文件读取到文本字段

转载 作者:行者123 更新时间:2023-12-02 05:39:35 24 4
gpt4 key购买 nike

我正在尝试使用 Java 读取 txt 文件。我想将内容分开。

txt文件的内容示例为:

[t]
Harry Potter
[a]
J.K Rowling

[c]
Once Upon a time
there was a wizard name Harry Potter
The End.

我想将带有 [c] 的文本放入名为 txtContent 的文本字段中,但现在发生的情况是只有第一行在 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();
}
}

最佳答案

当您检测到当前是否位于 [a] 行时,您可以读取 nextLine 并中断循环。

使用BufferedReader而不是FileReader

示例:

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();
}

关于Java Swing 将文件读取到文本字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24622391/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com