ISE-ComProg-After-Midterm/Week9/Assignment9/src/CSVUtility.java

57 lines
1.8 KiB
Java

//This Code is written bt Siwat Sirichai
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class CSVUtility {
/**
* reads all lines in given filename into an array of String
*
* @param filename
* @return array of String, each element in array is each line in file
* @throws FileNotFoundException
*/
public static String[] readFile(String filename) throws FileNotFoundException {
// ENTER CODE HERE
Scanner sc = new Scanner(new File(filename)); // Create a Scanner to take in the file at path filename
int length = 0; //Create a length variable and initialize it to zero
for (length = 0; sc.hasNext(); length++)
sc.nextLine();
sc.close(); //Close the Scanner to prevent resource leak
String[] filedata = new String[length];
sc = new Scanner(new File(filename)); //Reinitialize the closed scanner
for (int i = 0; i < length; i++)
filedata[i] = sc.nextLine();
sc.close(); //Close the Scanner to prevent resource leak
return filedata; //Return
}
/**
* read given CSV file into 2D array of String
*
* @param filename CSV file
* @param header true if CSV file has a header line. The first line is header.
* The data start from second line.
* @return
* @throws FileNotFoundException
*/
public static String[][] readCSV(String filename, boolean header) throws FileNotFoundException {
// ENTER CODE HERE
String[] data = readFile(filename);
int lineOffset = header ? 1 : 0;
int maxElement = 0;
for (int i = lineOffset; i < data.length; i++)
maxElement = Math.max(data[i].split(",").length, maxElement);
String[][] csv = new String[data.length - lineOffset][maxElement];
for (int i = lineOffset; i < data.length; i++)
csv[i - lineOffset] = data[i].split(",");
return csv;
}
}