如何从文件中读取java中的所有数据并形成数组列表
这是我到目前为止所知道的,但是idk知道如何从参数获取文件名输入如何从文件中读取java中的所有数据并形成数组列表,java,Java,这是我到目前为止所知道的,但是idk知道如何从参数获取文件名输入 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 这看起来像是您试图读取的CSV文件。 我建议使用一个库,例如 如果您使用的是Maven,请将以下内容添加到
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
这看起来像是您试图读取的CSV文件。 我建议使用一个库,例如 如果您使用的是Maven,请将以下内容添加到POM.xml中:
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));
}
代码:
请显示您当前解决问题的尝试。请提供最小可复制样本,看起来像CSV文件。使用库,例如。或者,您也可以逐行读取它们,按逗号拆分并将它们存储在数组中。
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));
}
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>5.1</version>
</dependency>
compile "com.opencsv:opencsv:5.1"
// 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]);
}