我有一个包含以下格式文本的文件:
text:text2:text3
text4:text5:text6
text7:text8:text9
现在我想做的是读取第一行,将“:”处的单词分开,并将3个字符串保存到不同的变量中。然后,在让程序读取下一行并一遍又一遍地执行相同的操作之前,将这些变量用作方法的参数。到目前为止,我已经得到了:
public static void main(String[] args) {
BufferedReader reader = null;
try {
File file = new File("C://Users//Patrick//Desktop//textfile.txt");
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
另外,我已经尝试过这种分离(尽管不确定数组是最好的选择:
String[] strArr = sCurrentLine.split("\\:");
最佳答案
使用 String[] parts = line.split(":");
获取包含 text
、text2
等的数组。然后可以循环遍历 parts
并对列表中的每个项目调用您想要的方法。
您原来的分割不起作用,因为 :
不是正则表达式中的特殊字符。当您尝试实现的分割使用特殊字符时,您只需使用转义字符。
更多信息here 。
关于java - 读取文件,一次一行并运行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46492234/