我不明白你爲什麼你的數據在同一行:「ID名稱編號1 Raj 1234 2 Ramesh 2345 3 Jayesh 3467」,而不是在每行的記錄。然後,你說它是CSV。 CSV是逗號分隔值。所以我希望你的列以「,」分隔。所以我會認爲你的數據其實是這樣的:
Id,Name,Number
1,Raj,1234
2,Ramesh,2345
3,Jayesh,3467
我會考慮你沒有在你的問題上做出介紹的努力。
此外,我不明白你想要做什麼與具有相同id的行的值。你說你不想重複,但你沒有解釋如何處理重複值(保留第一個值,連接,如果是整數,則添加...)。讓我們考慮一下我們想要保持與第一行相關的值。
所以,你可以這樣做:
public static void main(String[] args) throws IOException {
File inputFolder = new File("yourFolderPath");
Set<String> alreadyMetNames = new HashSet<>();
File output = File.createTempFile("output", ".csv");
try (FileWriter fw = new FileWriter(output); BufferedWriter bw = new BufferedWriter(fw)) {
bw.write("Id,Name,Number");
bw.newLine();
for (File file : inputFolder.listFiles()) {
try (FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr)) {
String line;
// Search the header line
while ((line = br.readLine()) != null) {
if (line.startsWith("Id")) break;
}
// Start to parse the file at the first row containing data
while ((line = br.readLine()) != null) {
String[] split = line.split(",");
if (alreadyMetNames.add(split[1])) {// If the name has not already been met
bw.write(line);
bw.newLine();
}
}
}
}
}
System.out.println("Your file is here : " + output.getAbsolutePath());
}
這段代碼創建一個新文件concatening其他文件內容的作家。然後它對每個文件進行迭代,搜索標題行,最後將標題行下面的數據內容寫入最終的輸出文件。在編寫行時,它會考慮不重寫已滿足的id行。