[英]Java: Splitting a file into a string for each line?
Hi I'm struggling to have my code read each line and save it into a String for each individual line. 嗨,我正在努力让我的代码读取每一行并将其保存到每一行的String中。 My code is below to load the text file but I can't seem to split it, I can get the first line split and that is it.
我的代码在下面以加载文本文件,但我似乎无法拆分它,我可以拆分第一行,就是这样。 I'm not brilliant at Java but I'm trying to load a text file that has 4 lines and I need to split that code from the file into different strings.
我在Java方面并不出色,但是我正在尝试加载一个包含4行的文本文件,我需要将该代码从文件中拆分为不同的字符串。 I can get it to get the first line of code but that's about it.
我可以得到它来获得第一行代码,但仅此而已。
Load.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String nextLine = reader.readLine();
if ( nextLine != null && nextLine.startsWith("Title:")) {
title = nextLine.substring(6);
panel.showText(title);
nextLine = reader.readLine();
}
reader.close();
} catch (IOException e1) {
System.err.println("Error while reading the file");
}
}
}
});
I think below may be useful https://kodejava.org/how-do-i-read-text-file-content-line-by-line-using-commons-io/ . 我认为以下内容可能有用:https://kodejava.org/how-do-i-read-text-file-content-line-by-line-using-commons-io/ 。
This suggests FileUtils from apache commons. 这表明来自Apache Commons的FileUtils。 Copied from the above site.
从以上站点复制。
File file = new File("sample.txt");
try {
List<String> contents = FileUtils.readLines(file);
// Iterate the result to print each line of the file.
for (String line : contents) {
System.out.println(line);
}
}
while(nextLine != null){
if ( nextLine != null && nextLine.startsWith("Title:")) {
title = nextLine.substring(6);
panel.showText(title);
nextLine = reader.readLine();
}
}
reader.close();
should do it 应该做
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.