Java Scanner class
If we see about Scanner and BufferedReader classes used to read stream contents, Scanner class mainly used to parsing tokens from the contents of the stream. But BufferedReader just reads the stream and does not do any special parsing like Scanner. For parsing we can pass those BufferedReader objects to a scanner as the source of characters or string to parse.
The other difference is BufferedReader is synchronized and Scanner is non-synchronized. Also from JDK 6 we have got 1 KB of character buffer for Scanner and 8 KB of character buffer for BufferedReader .
Use Scanner if need to parse the file or use BufferedReader just to read the file.
Next we will see simple example of parsing CSV file using Scanner class.
training.csv
1,Java Basics,4 weeks,INR 3000,
2,Oracle,5 weeks,INR 4500,
3,ASP.NET,6 weeks,INR 5000,
4,EJP,3 weeks,INR 4000,
5,Hibernate,4 weeks,INR 2000,
6,Spring,8 weeks,INR 6000,
TrainingBean.java
public class TrainingBean {
private int id;
private String course;
private String duration;
private String fees;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
public String getFees() {
return fees;
}
public void setFees(String fees) {
this.fees = fees;
}
@Override
public String toString() {
return "ID:"+id+"\t Course:"+course+"\t Duration:"+duration+"\t Fees:"+fees;
}
}
ScannerTest.java
public class ScannerTest {
public static void main(String[] args) throws FileNotFoundException {
ArrayList<TrainingBean> trainingList = parseTrainingDetails("D://training.csv");
displayTrainingDetails(trainingList);
}
public static ArrayList<TrainingBean> parseTrainingDetails(String file) {
ArrayList<TrainingBean> list = new ArrayList<TrainingBean>();
try {
Scanner scan = new Scanner(new File(file));
scan.useDelimiter(",");
int i = 1;
TrainingBean bean = new TrainingBean();
while (scan.hasNext()) {
String value = scan.next().trim();
if (value.length() == 0)
break;
if (i == 1) {
bean.setId(Integer.parseInt(value));
} else if (i == 2) {
bean.setCourse(value);
} else if (i == 3) {
bean.setDuration(value);
} else if (i == 4) {
bean.setFees(value);
i = 0;
list.add(bean);
bean = new TrainingBean();
}
i++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return list;
}
public static void displayTrainingDetails(ArrayList<TrainingBean> list) {
for (TrainingBean trainingBean : list) {
System.out.println(trainingBean.toString());
}
}
}
OUTPUT:
ID:1 Course:Java Basics Duration:4 weeks Fees:INR 3000
ID:2 Course:Oracle Duration:5 weeks Fees:INR 4500
ID:3 Course:ASP.NET Duration:6 weeks Fees:INR 5000
ID:4 Course:EJP Duration:3 weeks Fees:INR 4000
ID:5 Course:Hibernate Duration:4 weeks Fees:INR 2000
ID:6 Course:Spring Duration:8 weeks Fees:INR 6000