Sometimes we need to read data from a CSV file as per requirement. You can easily read the data from CSV file by following the below steps:
- Write the following Maven configuration in pom.xml file in your project:
<dependency>
<groupid>net.sf.opencsv</groupid>
<artifactid>opencsv</artifactid>
<version>2.3</version>
</dependency>
- Now define the model class in which you want to store data from CSV.
public class TempModel
{
private String customId;
private String tickitStatus;
private String tickitType;
private String tickitMsgBody;
private String tickitStringStartDate;
private String tickitStringEndDate;
public String getCustomId()
{
return customId;
}
public void setCustomId(String customId)
{
this.customId = customId;
}
public String getTickitStatus()
{
return tickitStatus;
}
public void setTickitStatus(String tickitStatus)
{
this.tickitStatus = tickitStatus;
}
public String getTickitType()
{
return tickitType;
}
public void setTickitType(String tickitType)
{
this.tickitType = tickitType;
}
public String getTickitMsgBody()
{
return tickitMsgBody;
}
public void setTickitMsgBody(String tickitMsgBody)
{
this.tickitMsgBody = tickitMsgBody;
}
public String getTickitStringStartDate()
{
return tickitStringStartDate;
}
public void setTickitStringStartDate(String tickitStringStartDate)
{
this.tickitStringStartDate = tickitStringStartDate;
}
public String getTickitStringEndDate()
{
return tickitStringEndDate;
}
public void setTickitStringEndDate(String tickitStringEndDate)
{
this.tickitStringEndDate = tickitStringEndDate;
}
}
- Now write the below method to read data from CSV file:
/**
* This methos is used to red data fro CSV file
* @param uploadedInputStream
*/
public void readDataFromCSV(InputStream uploadedInputStream)
{
TicketModel ticketModel = null;
UserResponse userResponse = new UserResponse();
try
{
ColumnPositionMappingStrategy strat = new ColumnPositionMappingStrategy();
strat.setType(TempModel.class);
// The fields to bind do in your JavaBean
String[] columns = new String[] { "customId", "tickitStatus", "tickitType","tickitMsgBody", "tickitStringStartDate","tickitStringEndDate" };
strat.setColumnMapping(columns);
CsvToBean csv = new CsvToBean();
CSVReader csvReader;
csvReader = new CSVReader(new InputStreamReader(uploadedInputStream), ',', '\"', 1);
List list = csv.parse(strat, csvReader);
for (TempModel tempModel : list)
{
logger.debug("After Read line");
logger.debug(tempModel.getCustomId());
}
}
catch (Exception e)
{
e.printStackTrace();
logger.error("failed", e);
}
finally
{
if (uploadedInputStream != null)
{
try
{
uploadedInputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
In the above example "readDataFromCSV" method will take CSV file as inputStream and read data from CSV file and store that data into list which is type of TempModel.
Hope this will help you :)
0 Comment(s)