我在 .txt 檔案中有以下示例資料
111, Sybil, 21
112, Edith, 22
113, Mathew, 30
114, Mary, 25
所需的輸出是
[{"number":"111","name":"Sybil","age":"21" },
{"number":"112","name":"Edith","age":"22"},
{"number":"113","name":"Mathew","age":"30"},
"number":"114","name":"Mary","age":"25"]
可悲的是,我并沒有走多遠,因為我似乎無法從每一行中獲取價值。相反,這是顯示的內容
[一二三]
private void loadFile() throws FileNotFoundException, IOException {
File txt = new File("Users.txt");
try (Scanner scan = new Scanner(txt)) {
ArrayList data = new ArrayList<>() ;
while (scan.hasNextLine()) {
data.add(scan.nextLine());
System.out.print(scan.nextLine());
}
System.out.print(data);
}
我將不勝感激任何幫助。謝謝你
uj5u.com熱心網友回復:
不太清楚要求。如果您只需要知道如何獲取這些值,請使用String.split()組合 with Scanner.nextLine()。
以下代碼:
private void loadFile() throws FileNotFoundException, IOException {
File txt = new File("Users.txt");
try (Scanner scan = new Scanner(txt)) {
ArrayList data = new ArrayList<>();
while (scan.hasNextLine()) {
// split the data by ", " and split at most (3-1) times
String[] input = scan.nextLine().split(", ", 3);
data.add(input[0]);
data.add(input[1]);
data.add(input[2]);
System.out.print(scan.nextLine());
}
System.out.print(data);
}
}
輸出如下,您可以自己進一步修改:
[111, Sybil, 21, 112, Edith, 22, 113, Mathew, 30, 114, Mary, 25]
但是,如果您還需要所需的格式,我能得到的最接近的方法是使用 aHaspMap并將其放入ArrayList.
以下代碼:
private void loadFile() throws FileNotFoundException, IOException {
File txt = new File("Users.txt");
try (Scanner scan = new Scanner(txt)) {
ArrayList data = new ArrayList<>();
while (scan.hasNextLine()) {
// Create a hashmap to store data in correct format,
HashMap<String, String> info = new HashMap();
String[] input = scan.nextLine().split(", ", 3);
info.put("number", input[0]);
info.put("name", input[1]);
info.put("age", input[2]);
// Put it inside the ArrayList
data.add(info);
}
System.out.print(data);
}
}
輸出將是:
[{number=111, name=Sybil, age=21}, {number=112, name=Edith, age=22}, {number=113, name=Mathew, age=30}, {number=114, name=Mary, age=25}]
希望這個答案對您有所幫助。
uj5u.com熱心網友回復:
目前,您正在跳過行,以參考Scanner::nextLine檔案:
此方法回傳當前行的其余部分,不包括末尾的任何行分隔符。位置設定為下一行的開頭。
因此,您在串列中添加一行并將下一行寫入控制臺。
要從每一行獲取資料,您可以使用String::split支持 RegEx 的方法。(例如"line of my file".split(" "):)
uj5u.com熱心網友回復:
我們可以使用流來撰寫一些緊湊的代碼。
首先我們定義 arecord來保存我們的資料。
Files.lines將您的檔案讀入記憶體,產生一個字串流,每行一個。
我們呼叫Stream#map產生另一個流,一系列字串陣列。每個陣列包含三個元素,即每行中的三個欄位。
我們map再次呼叫,這次是為了產生一個Person物件流。我們通過決議行的三個欄位中的每一個并將其傳遞給建構式來構造每個人物件。
我們呼叫Stream#toList將這些人員物件收集到一個串列中。
我們呼叫List#toString來生成表示人員物件串列內容的文本。
record Person ( int id , String name , int age ) {}
String output =
Files
.lines( Paths.of("/path/to/Users.txt" ) )
.map( line -> line.split( ", " ) )
.map( parts -> new Person(
Integer.parseInt( parts[ 0 ] ) ,
parts[ 1 ] ,
Integer.parseInt( parts[ 2 ] )
) )
.toList()
.toString()
;
如果默認Person#toString方法的格式不適合您,請添加該方法的覆寫以生成所需的輸出。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/474612.html
下一篇:迭代物件并替換值
