CSV с двумя разделителями
Я пытаюсь прочитать CSV с двумя разделителями, который имеет следующий формат:
Payment Date,Amount,Member No/branchno
2018/01/25,58,294416/0
первая часть - это дата, а последний столбец - это столбец, с которым я сталкиваюсь. Мне нужно разделить этот последний столбец на два столбца после косой черты.
моя проблема в том, что я не знаю, как отделить последний столбец, не затрагивая первый столбец, любая помощь очень ценится.
Я уже могу прочитать CSV и разделить запятыми. Вот код для чтения через CSV:
public ArrayList<String[]> ReadCSVFile(File DataFile)
{
try(BufferedReader reader = new BufferedReader (new FileReader(DataFile));){
//while loop to read through the data, while bufferedreader is not null-do ....
while(reader.readLine()!= null)
{
String read = reader.readLine();//bufferedreader string variable
String[] OneRow = read.split(","||"/");
rs2.add(OneRow);
System.out.println(Arrays.toString(OneRow));
//
}
//BufferedReader to Read through CSV Contents
reader.close();
}//end try
catch(Exception ex){
String errmsg = ex.getMessage();
//System.out.println("File not Found: "+errmsg);
}//end exception handling
2 ответа
Вы можете сделать что-то вроде этого;
while (reader.readLine() != null) {
String read = reader.readLine();// bufferedreader string variable
String[] rawRow = read.split(",");
String lastEntry = rawRow[rawRow.length - 1]; // this contains Member No/branchno
String[] properLastEntry = lastEntry.split("/"); // this contains Member No, branchno
String[] oneRow = new String[rawRow.length + 1];
System.arraycopy(rawRow, 0, oneRow, 0, rawRow.length - 1);
System.arraycopy(properLastEntry, 0, oneRow, oneRow.length - 2, 2);
}
Если вы не хотите жестко кодировать длину 2
в properLastEntry
массив, вы можете сделать что-то вроде этого вместо
while (reader.readLine() != null) {
String read = reader.readLine();// bufferedreader string variable
String[] rawRow = read.split(",");
String lastEntry = rawRow[rawRow.length - 1]; // this contains Member No/branchno
String[] properLastEntry = lastEntry.split("/"); // this contains Member No, branchno as entries
// create a memory which can contain rawRow and properLastEntry in a single
// array
String[] oneRow = new String[rawRow.length - 1 + properLastEntry.length];
// copy the data for the finalRow
System.arraycopy(rawRow, 0, oneRow, 0, rawRow.length - 1);
System.arraycopy(properLastEntry, 0, oneRow, oneRow.length - properLastEntry.length,
properLastEntry.length);
}
Вы хотите разделить строку на основе двух разделителей, чтобы вы могли упомянуть несколько разделителей следующим образом
split(",|/")
Пожалуйста, перейдите по ссылке ниже. Используйте строку split() с несколькими разделителями