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

54 lines
2.1 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++) //Find Line amount | Loop until there's no next line,each loop length++
sc.nextLine();// Go to the next line
sc.close(); //Close the Scanner to prevent resource leak
String[] fileData = new String[length]; //create a 1D array to store file data
sc = new Scanner(new File(filename)); //Reinitialize the closed scanner
for (int i = 0; i < length; i++)
fileData[i] = sc.nextLine(); //Send line i to array fileData at index i-1
sc.close(); //Close the Scanner to prevent resource leak
return fileData; //Return array filled with file data
}
/**
* 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); //Read the file
int lineOffset = header ? 1 : 0; //do we have header? if yes, start at line 2
String[][] csv = new String[data.length - lineOffset][];
for (int i = lineOffset; i < data.length; i++) //Go through all rows
csv[i - lineOffset] = data[i].split(","); //Array.split(String delimiter) return a 1D array with each element seperated by the delimiter
return csv; //Send back the CSV file
}
}