[英]How to Filter a txt file in java
作為輸入,我有一個包含房間列表的文件。 每個房間都有以下信息:(文件的1行)
ID;name;phonenumber;PIN e.g.:
1234;A 0.12;1234;123456789 (ID is same as [first] phonenumber)
2345;A 0.12;2345;123456789 (A room can have more than 1 phonenumber - in a new line like in the example)
現在我需要一個java程序,它返回一個這樣的列表:
Example Input: 1127,A 0.01,1127,1 2476,A 0.01,2476,1 2309,A 0.01,2309,1 2306,A 0.01,2306,1 2706,A 0.01,2706,1 2757,A 0.01,2757,1 Generates Output: 1127,A 0.01,1127,2476,2309,2306,2706,2757,1
ID;姓名;電話號碼1;...;電話號碼N;PIN
如果 2 條線路的房間相同,則此代碼(不帶主要功能)向現有電話號碼添加第二個電話號碼。
public static String duplicateNumbers(String s, String x) {
String result = s;
if(compareString(s, x)) {
result = result.substring(0, 21)
+ x.charAt(21) + x.charAt(22) + x.charAt(23) + x.charAt(24)
+ result.substring(20);
}
return result;
}
public static boolean compareString(String s, String x) {
for(int i = 5; i < 10; i++) {
if(s.charAt(i) != x.charAt(i)) return false;
}
return true;
}
ß
嘗試這個:
String fileName = "D:/test.txt";
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
stream.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
我希望這對你需要的東西有幫助。 我使用了 Apache Common CSV。 您可以在此處找到更多信息https://www.baeldung.com/apache-commons-csv
文件.csv
ID;name;phonenumber;PIN; 1127;A 0.01;1127;1; 2476;A 0.01;2476;1; 2309;A 0.01;2309;1; 2306;A 0.01;2306;1; 2706;A 0.01;2706;1; 2757;A 0.01;2757;1; 2722;B 0.01;2722;1; 2723;B 0.01;2723;1;
@Test public void testForAlphaOmega() throws IOException { @Getter class ROOM { String id; String name; String phoneNumber; String pin; private ROOM(String id, String name, String phoneNumber, String pin){ this.id = id; this.name = name; this.phoneNumber = phoneNumber; this.pin = pin; } private ROOM(CSVRecord record){ this.id = record.get("ID"); this.name = record.get("name"); this.phoneNumber = record.get("phoneNumber"); this.pin = record.get("PIN"); } } try ( Reader reader = Files.newBufferedReader(Paths.get("....PATH_OF_FILE")); CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT .withHeader("ID", "name", "phoneNumber", "PIN") .withIgnoreHeaderCase() .withFirstRecordAsHeader() .withDelimiter(';') .withTrim()) ) { List<ROOM> rooms = new ArrayList<>(); csvParser.getRecords().stream().map(ROOM::new).collect(groupingBy(ROOM::getName)).forEach((key,val) -> rooms.add(new ROOM(val.get(0).getId(), val.get(0).getName(), val.stream().map(ROOM::getPhoneNumber).collect(Collectors.joining(",")),val.get(0).getPin()))); rooms.forEach(item -> System.out.println(item.getId() + ";" + item.getName() +";" + item.getPhoneNumber() + ";" + item.getPin())); } }
結果
\n 2722;B 0.01;2722,2723;1\n 1127;A 0.01;1127,2476,2309,2306,2706,2757;1\n
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.