//PersonStreamTest – text file read using BinaryStream, Reader
public class PersonStreamTest {
public static void load1(String filename) {
FileInputStream fis;
try {
fis = new FileInputStream(filename);
System.out.println("load1 file import: " + filename);
int c = 0;
while ((c = fis.read()) != -1) {
System.out.println((char)c);
}
fis.close();
System.out.println("load1 successfully");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void load2(String filename) {
FileReader fr;
try {
fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
System.out.println("load2 file import: " + filename);
String line = "";
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
fr.close();
System.out.println("load2 successfully");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void load3(String filename) {
FileReader fr;
try {
fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
System.out.println("load3 file import: " + filename);
String delimiter = ",";
String line = "";
while ((line = br.readLine()) != null) {
try {
// use comma as separator
String[] items = line.split(delimiter);
String name = items[0];
int age = Integer.parseInt(items[1]);
double weight = Double.parseDouble(items[2]);
double height = Double.parseDouble(items[3]);
Gender gender = items[4].equals("FEMALE") ? Gender.FEMALE : Gender.MALE;
// add Person into person array
Person p = new Person(name, age, weight, height, gender);
System.out.println(p);
}
catch (NumberFormatException e) {
System.out.println("Error(parseInt or parseDouble)!");
}
}
br.close();
fr.close();
System.out.println("load3 successfully");
} catch (FileNotFoundException e) {
System.out.println("Error! FileNotFoundException");
} catch (IOException e) {
System.out.println("Error! IOException");
}
}
public static void main(String[] args) {
String filename = "PersonList.csv";
// command line arguments
if (args.length >= 1) {
filename = args[0];
System.out.println("args0=" + filename);
}
load1(filename); // using binary stream
load2(filename); // using text file reader & buffered reader
load3(filename); // using text file reader & buffered reader & parse
}
}