这里对 java 非常非常陌生。目前,我有代码从单个文本文件中提取数据,并以我可用的格式解析数据(见下文)。不幸的是,这要求我必须更改每次运行的文件名。理想情况下,我希望通过循环文件名字符串数组来收集数据来自动化它。
知道如何传递文件名数组并循环遍历每个名称吗?
package weatherfiledata;
import java.io.*;
/**
*
*
*/
public class WeatherFileData {
int month[] = new int[8760];
int day[] = new int[8760];
int hour[] = new int[8760];
int db[] = new int[8760];
int wb[] = new int[8760];
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int count;
//here i would declare the array of fileNames and start the loop
//String fileNames[] = {"fileName1","fileName2"...};
//for(count = 0; count < fileNames.length; count++){
// TODO code application logic here
//create an object named "DataInput" of type "WeatherFileData"
WeatherFileData DataInput = new WeatherFileData();
DataInput.InputData(DataInput);
//display data
int i;
for(i=0; i<DataInput.month.length; i++) {
System.out.print(DataInput.wb[i] +",");
}
//} end of loop
}
void InputData(WeatherFileData DataInput) {
BufferedReader br = null;
try {
String sCurrentLine;
//this is where I currently have to change the fileName each time;
//I would like to be able to use the fileName array loop to automate
br = new BufferedReader(new FileReader("fileName1.txt"));
int i=0;
while ((sCurrentLine = br.readLine()) != null) {
String arr[] = sCurrentLine.split("\t");
DataInput.month[i] = Integer.parseInt(arr[0]);
DataInput.day[i] = Integer.parseInt(arr[1]);
DataInput.hour[i] = Integer.parseInt(arr[2]);
DataInput.wb[i] = Integer.parseInt(arr[3]);
DataInput.db[i] = Integer.parseInt(arr[4]);
i++;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
最佳答案
您应该首先为文件名引入一个字符串变量:
br = new BufferedReader(new FileReader(filename));
并将此变量作为参数传递给您的方法:
void inputData(WeatherFileData dataInput, String filename) {
然后,您可以在数组中维护这些文件的列表:
String[] filenames = new String[5];
filenames[0] = "fileName1.txt";
...
并通过以下方式迭代它们:
for(String filename : filenames){
WeatherFileData dataInput = new WeatherFileData();
dataInput.inputData(dataInput, filename);
... // Do what you want with DataInput
}
作为最后一条评论,请注意您不需要这样做:
dataInput.inputData(dataInput, filename);
这样会更好:
dataInput.inputData(filename);
但在函数 inputData()
中写下:
this.month[i] = Integer.parseInt(arr[0]);
而不是这个:
dataInput.month[i] = Integer.parseInt(arr[0]);
(我还删除了对象和方法名称中的大写首字母,这是惯例)
关于具有文件名数组的 Java InputData 读/写循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30426176/