[英]Read file, one line at a time and run code
我有一個包含以下格式文本的文件:
文字:文字2:文字3
文字 4:文字 5:文字 6
文字 7:文字 8:文字 9
現在我想做的是閱讀第一行,將“:”處的單詞分開,並將這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();
}
}
另外,我已經嘗試過這種分離(雖然不確定 Array 是最好的選擇:
String[] strArr = sCurrentLine.split("\\:");
使用String[] parts = line.split(":");
獲取包含text
、 text2
等的數組。然后您可以遍歷parts
並使用列表中的每個項目調用所需的方法。
您原來的拆分不起作用,因為:
不是正則表達式中的特殊字符。 當您嘗試實現的拆分使用特殊字符時,您只需使用轉義字符。
更多信息在這里。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.