Java:将文件拆分为每行的字符串?
嗨,我正在努力让我的代码读取每一行并将其保存为每一行的字符串。下面是我加载文本文件的代码,但我似乎无法拆分它,我可以拆分第一行,就是这样。我不擅长Java,但我正在尝试加载一个有4行的文本文件,我需要将该文件中的代码拆分为不同的字符串。我可以让它得到第一行代码,但仅此而已Java:将文件拆分为每行的字符串?,java,split,line,bufferedreader,Java,Split,Line,Bufferedreader,嗨,我正在努力让我的代码读取每一行并将其保存为每一行的字符串。下面是我加载文本文件的代码,但我似乎无法拆分它,我可以拆分第一行,就是这样。我不擅长Java,但我正在尝试加载一个有4行的文本文件,我需要将该文件中的代码拆分为不同的字符串。我可以让它得到第一行代码,但仅此而已 Load.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEv
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");
}
}
}
});
应该这样做我认为下面可能有用 这建议使用apachecommons中的FileUtils。复制自上述网站
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);
}
}
File File=new文件(“sample.txt”);
试一试{
列表内容=FileUtils.readLines(文件);
//迭代结果以打印文件的每一行。
for(字符串行:内容){
系统输出打印项次(行);
}
}
为什么要检查两次nextLine!=在哪里添加while循环比在代码本身上更多,如果我真的被它困扰的话,我会把它分到一个方法中,它可能应该是请在这里添加该链接的相关细节,因为,如果该链接的内容以后更改,你在这里的答案可能会变差。
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);
}
}