I am trying to save data separately by using ArrayList. However, after saving one data into the array, it skips one line then saves the data. Please help me with this problem.
private void readCSVFile(String tickerCode, File file) {
System.out.println("Reading file " + tickerCode);
System.out.println(file.getPath());
try {
ArrayList<List<String>> line = new ArrayList<>();
BufferedReader br = new BufferedReader(new FileReader(file));
CSVReaderHeaderAware csvReader = new CSVReaderHeaderAware(br);
int numLine = 0;
String[] values;
while ((values = csvReader.readNext()) != null) {
ArrayList<String> data = new ArrayList<>();
data.add(values[0]);
data.add(values[1]);
data.add(values[2]);
data.add(values[3]);
data.add(values[4]);
data.add(values[5]);
data.add(values[6]);
line.add(data);
if(numLine == 0){
System.out.print("StartDate = "+ values[0]);
}
if((csvReader.readNext() == null)){
System.out.println(" EndDate = " + values[0]);
}
++numLine;
}
As mentioned in a comment, you cannot use csvReader.readNext()
inside the loop as well to check if the next element is null
, because it will actually read the next line. So what you can do is keep the last processed row's date in a variable, and then print it as the EndDate after the while loop is finished.
ArrayList<List<String>> line = new ArrayList<>();
BufferedReader br = new BufferedReader(new FileReader(file));
CSVReaderHeaderAware csvReader = new CSVReaderHeaderAware(br);
int numLine = 0;
String[] values;
String endDate = null;
while ((values = csvReader.readNext()) != null) {
ArrayList<String> data = new ArrayList<>();
data.add(values[0]);
data.add(values[1]);
data.add(values[2]);
data.add(values[3]);
data.add(values[4]);
data.add(values[5]);
data.add(values[6]);
line.add(data);
if(numLine == 0){
System.out.print("StartDate = "+ values[0]);
}
endDate = values[0];
++numLine;
}
if (endDate != null) { // Need to check null in case your CSV didn't have any rows
System.out.println(" EndDate = " + endDate);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.