Using FileReader in a non-main method
I can read a CSV file into my Java main method using the code below.
What I want to achieve is to be able to use the below code in a method
that is not my main method. I want to be able to call this method from my
main so that I can read a CSV file without having all this code cluttering
my main. How do I do this?
FYI the CSV file has 2 columns of doubles, hence the use of the double [][].
public static void main(String[] args) throws IOException {
double [][] data = new double [100][2];
File file = new
File("C:\\Users\\Username\\Java\\Test2\\First\\src\\Program1\\prac.csv");
int row = 0;
int col = 0;
BufferedReader bufRdr = new BufferedReader(new FileReader(file));
String line = null;
//read each line of text file
while((line = bufRdr.readLine()) != null && row < data.length) {
StringTokenizer st = new StringTokenizer(line,",");
while (st.hasMoreTokens()) {
//get next token and store it in the array
data[row][col] = Double.parseDouble(st.nextToken());
col++;
}
col = 0;
row++;
}
}
No comments:
Post a Comment