-1
public ArrayList<ITemperature> readDataFromFile(String fileName);
  //read all data from the weather data file

This would be the interface. If given a file, how would I be able to read it and separate them into an array list and keep them in columns?

Ex(if file contained this, how can I do it):

Temperature, Year, Month_Avg, Country, Country_Code
1.62425, 2000, Jan, Afghanistan, AFG
1.92871, 2000, Feb, Afghanistan, AFG
7.48463, 2000, Mar, Afghanistan, AFG

This is what i have so far but idk how to get the file name input from the paramater.

public ArrayList<ITemperature> readDataFromFile(String fileName){
     // read all data from the weather data file 
    File file = new File("C:\\Users\\JTPD_\\eclipse-workspace\\Climate Change Analysis\\data\\world_temp_2000-2016.csv");
    BufferedReader br = new BufferedReader(new FileReader(file));
    }

1 Answers1

1

This looks like a CSV file that you're trying to read. I would recommend using a library such as OpenCSV.

If you're using Maven, add this to your POM.xml:

<dependency>
    <groupId>com.opencsv</groupId>
    <artifactId>opencsv</artifactId>
    <version>5.1</version>
</dependency>

Gradle:

compile "com.opencsv:opencsv:5.1"

Code:

// This is for Java 10. If you're using Java 8 or lower, you can't use var.

// Filename should be entire file Path
var isr = new InputStreamReader(new FileInputStream(fileName, StandardCharsets.UTF_8));

// withSkipLines will skip the header row. If you want to retain it, remove skipLines
var reader = new CSVReader(isr).withSkipLines(1).build();;

String[] lineArray;
while ((lineArray= csvReader.readNext()) != null) {
     System.out.println("Temperature: " + lineArray[0]);
     System.out.println("Year: " + lineArray[1]);
     System.out.println("Month_Avg: " + lineArray[2]);
     System.out.println("Country : " + lineArray[3]);
     System.out.println("Country_Code : " + lineArray[4]);
}
Adithya Upadhya
  • 2,239
  • 20
  • 28