[英]Read line by line from text file and save each line to different cell in array
我正在嘗試將文本文件中的每一行拆分為數組中的單元格。 我可以使用split函數而不計算行數來創建數組嗎?
我正在使用Scanner
從掃描Scanner
讀取文件。 該文件在每一行中包含以下格式: number_number
我想將number_number
作為字符串保存到Array中的單元格中。 但是,我不知道文本文件中可以設置幾行以設置數組大小。 我不想t want to use
LinkedList`,請使用不會有太多行的假設。 是否可以從文件讀取並將每一行保存到數組的單元格中? 將方法從掃描儀更改為另一種方法沒有問題。
當前我代碼中的問題是它僅將第一行保存在文件中。
public String[] readFromFileToStringArray(String s) {
Scanner scanner = null;
try {
scanner = new Scanner(new File(s));
} catch (IOException e) {
e.printStackTrace();
}
String[] fileText = null;
if (scanner != null)
while (scanner.hasNext())
fileText = scanner.nextLine().split("\n");
return fileText;
}
當使用scanner.nextLine()
您將讀取文本直到\\n
字符為止,因此您所做的拆分是沒有意義的,因為行字符串中將沒有該字符。
您可以讀取所有文件,然后將其拆分:
public String[] readFromFileToStringArray(String s) {
String text = new String(Files.readAllBytes(Paths.get(s)),
StandardCharsets.UTF_8);
return text.split("\n");
}
但實際上,正如另一個回答所說的那樣,僅使用List
可能會更好
您是否應該更改將字符串添加到數組的方式?
fileText.add(scanner.nextLine());
要么:
List<String> list = new ArrayList<String>(Arrays.asList(fileText));
list.addAll(Arrays.asList(scanner.nextLine().splite("\n")));
String[] fileText = list.toArray();
List<String> lines = Files.readAllLines(pathToFile);
Java Files是最簡單的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.