我想讀取行的每一列值并使用分隔符列印列串列值,并通過在java中使用for回圈,我們從DB中獲取的資料作為串列物件每一行和每一列,列標題是用戶名,姓氏,名字,電子郵件ID,地址。在控制臺中列印列值。有人可以用邏輯幫助我嗎?提前致謝 。這樣,o/p 應該與 5 個引數列值的串列
uj5u.com熱心網友回復:
- 打開檔案
readLine()用方法讀取行
//open the file
String line;
while ((line = file.readLine()) != null) {
String[] result = line.split(";");
}
該split()方法允許您使用分隔符將字串拆分為String陣列。因此,每一行將是一個包含該行列的陣列。
uj5u.com熱心網友回復:
如果你真的想使用 for 回圈:
for (String line = file.readLine(); line != null; line = file.readLine()) {
String[] split = line.split("");
System.out.println(String.join(", ", split));
}
對于這樣的檔案:
User
Example
Person
exampleuser@gmail.com
它會列印:
U, s, e, r
E, x, a, m, p, l, e
P, e, r, s, o, n
e, x, a, m, p, l, e, u, s, e, r, @, g, m, a, i, l, ., c, o, m
uj5u.com熱心網友回復:
從什么讀??文本檔案還是 CSV 檔案?資料庫?無論資料來自何處,我都會假設它是從文本檔案中讀取的。在我看來(至少在我看來)你想在控制臺視窗中以表格樣式格式顯示檔案資料......像這樣:
User Name | Last Name | First Name | E-Mail ID | E-Mail Domain
=============================================================================
Creeper001 | Jones | Tom | tjones | @yahoo.com
BigSpender | Cash | Johnny | backtofolsom | @yahoo.com
TripWire | Whire | Trip | nevercaught | @hotmail.com
BigSplit | Ciccone | Madonna | ilikeitcreamy | @muchmusic.com
WhatThe... | Newhart | Bob | usetobegood | @gmail.com
=============================================================================
這當然來自如下所示的檔案資料:
我的資料檔案.txt:
reeper001, Jones, Tom, tjones, yahoo.com
BigSpender, Cash, Johnny, backtofolsom, yahoo.com
TripWire, Whire, Trip, nevercaught, hotmail.com
BigSplit, Ciccone, Madonna, ilikeitcreamy, muchmusic.com
WhatThe..., Newhart, Bob, usetobegood, gmail.com
話雖如此,您可以使用以下內容顯示上表:
String filePath = "MyDataFile.txt";
String header = String.format("%-12s | %-12s | %-12s | %-16s | %-20s",
"User Name", "Last Name", "First Name", "E-Mail ID", "E-Mail Domain");
String underline = String.join("", java.util.Collections.nCopies(header.trim().length(), "="));
System.out.println(header System.lineSeparator() underline);
File file = new File(filePath);
try (Scanner reader = new Scanner(file)) {
String line;
while (reader.hasNextLine()) {
line = reader.nextLine().trim();
if (line.isEmpty()) { continue; }
String[] lineParts = line.split("\\s*,\\s*"); // Comma is the most typical delimiter for CSV data.
System.out.printf("%-12s | %-12s | %-12s | %-16s | @%-20s%n",
lineParts[0], lineParts[1], lineParts[2], lineParts[3], lineParts[4]);
}
System.out.println(underline);
System.out.println();
}
catch (FileNotFoundException ex) {
System.out.println("Can Not Locate The File Specified: -> " file.getAbsolutePath());
}
請注意,Header 使用String#format()方法格式化,檔案資料使用Scanner#printf()方法格式化。兩者都以類似的方式作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/467856.html
上一篇:二維陣列平均值和總c
