基本上,我有一堆信息,我需要从文件中读取并将其放入2D数组中。 data.txt文件如下所示:
a 2016-10-03 Boston Type1 112
b 2016-05-02 Chicago Type2 150
c 2016-06-01 Denver Type3 1500
d 2016-08-26 NewYork Type4 80
谢谢!
答案 0 :(得分:-1)
你显然需要的是一个2D数组,它最终将由无限行组成,每行5列。要声明2D数组,首先需要确定每列的数据类型。例如,让我们看一下文件内容的第一行:
a 2016-10-03 Boston Type1 112
第一,我们有' a '这是一种字符串数据类型;
第二,我们有' 2016-10-03 ',这是一种日期数据类型,
第3个我们有'波士顿',它又是一个字符串数据类型,
第4个我们有' Type1 ',它又是一个String数据类型,
第五,最后我们有' 112 ',这很可能是整数数据类型。
如果要在2D Array中维护这些特定数据类型,则需要将数组声明为Object:
对象[] [] myArray = {};
如果您希望将这些数据类型保持为字符串,而这正是它们在文本文件中的真实含义,那么您需要将2D数组声明为字符串:
String [] [] myArray = {};
这取决于您和您如何决定应该如何处理从阵列中检索到的元素数据。
首先,您需要确定为数组维度所需的行数。为此,您需要知道数据文件中包含多少数据行。要做到这一点,我们需要制作一个简单的方法,以获得这个数量。让我们创建一个方法来计算文本文件中的文本行数,我们称之为 countFileLines():
private static int countFileLines(String filePath) {
try {
int count = 0;
try (InputStream inSt = new BufferedInputStream(new FileInputStream(filePath))) {
byte[] c = new byte[1024];
int readChars = 0;
boolean NoNewLine = false;
while ((readChars = inSt.read(c)) != -1) {
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n') { ++count; }
}
NoNewLine = (c[readChars - 1] != '\n');
}
if(NoNewLine) { ++count; }
inSt.close();
}
return count;
}
catch (FileNotFoundException ex) {
System.out.println("countFileLines() Method ERROR - File Not Found!");
}
catch (IOException ex) {
System.out.println("countFileLines() Method ERROR - IO Exception Encountered\n" + ex.getMessage());
}
return 0;
}
现在我们已经开始使用二维'String'数组:
// Let's get the number of data lines within file.
// If file is not in classpath then supply full path.
int dl = countFileLines("data.txt");
if (dl == 0) { System.exit(0); }
String[][] myArray = new String[dl][5];
在那里,现在我们已经声明并初始化了我们的2D字符串数组,以保持所提供的数据文件中数据行包含的总行数,并且我们已经将列设置为5,因为我们已经知道每个文件行由5个用空格分隔的字符串数据块组成。
现在我们所需要做的就是读入每个数据文件行(行)并将每个字符串块(列)放入2D字符串数组中它们各自的元素中。我们需要制作一个简单的自定义方法来执行任务。我们称之为 applyFileDataToArray():
private static String[][] applyFileDataToArray(String filePath, String[][] myArray) {
// declare and intialize a String variable to hold string
// data lines read from file.
String line = "";
// Declare and initialize a temporary 2D Array to fill with file data
// and return.
String[][] tmpArray = new String[myArray.length][myArray[0].length];
// Declare and iniialize a Integer variable to be used as a incremental
// index counter for our temporary 2D Array.
int cnt = 0;
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
// Read in each line of the data text file so as to place each
// line of data into the a temporary 2D String Array which will
// be ulimately returned...
while((line = br.readLine()) != null){
// Skip past blank lines in the text file and only process file lines
// which actually contain data.
if (!line.equals("")) {
// Each line of data within the data text file consists
// of a string with 5 data chunks each delimited with a
// whitespace. We place each data chunk into a String
// Array and then interate through this array and place
// each element into the 2D Array.
String[] tok = line.split(" ");
for (int i = 0; i < tok.length; i++) {
tmpArray[cnt][i] = tok[i];
}
// increment index counter...
cnt++;
}
}
// Data now acquired from file - Close the BufferReader
br.close();
}
// Trap IO Exceptions from the Bufferreader if any...
catch (IOException ex) {
System.out.println("\n\u001B[31mThe supplied data file could"
+ " not be found!\n\u001B[39;49m" + filePath);
}
// Return filled 2D Array
return tmpArray;
}
上面的方法得到了很好的评论,所以应该相对容易理解那里发生了什么。
现在,有了两个新方法,我们的“主要”代码看起来应该是这样的:
int dl = CountFileLines("data.txt");
if (dl == 0) { System.exit(0); }
String[][] myArray = new String[dl][5];
myArray = applyFileDataToArray("data.txt", myArray);
// Display the contents of our 2D Array to Console...
for (int i = 0; i < myArray.length; i++) {
System.out.println("\nROW " + (i+1) + ":");
for (int j = 0; j < 5; j++) {
System.out.println("\tColumn " + (j+1) + ": " + myArray[i][j]);
}
}
如前所述,如果要在2D Array的元素列中维护特定数据类型,则需要将2D Array声明并初始化为Object类型。您的“主要”代码将如下所示:
int dl = CountFileLines("data.txt");
if (dl == 0) { System.exit(0); }
Object[][] myArray = new Object[dl][5];
myArray = applyFileDataToArray("data.txt", myArray);
// Display the contents of our 2D Array to Console...
for (int i = 0; i < myArray.length; i++) {
System.out.println("\nROW " + (i+1) + ":");
for (int j = 0; j < 5; j++) {
System.out.println("\tColumn " + (j+1) + ": " + myArray[i][j]);
}
}
和我们的 applyFileDataToArray()方法会有所不同,以适应不同需要的数据类型。该方法现在看起来像:
private static Object[][] applyFileDataToArray(String filePath, Object[][] myArray) {
String line = "";
Object[][] tmpArray = new Object[myArray.length][myArray[0].length];
int cnt = 0;
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
// Read in each line of the data text file so as to place each
// line of data into the a temporary 2D Object Array which will
// be ulimately returned...
while((line = br.readLine()) != null){
// Skip past blank lines in the text file and only process file lines
// which actually contain data.
if (!line.equals("")) {
// Each line of data within the data text file consists
// of a string with 5 data chunks each delimited with a
// whitespace. We place each data chunk into a String
// Array and then interate through this array and place
// each element into the 2D Object Array with their respective
// data type.
String[] tok = line.split(" ");
tmpArray[cnt][0] = tok[0];
tmpArray[cnt][1] = cDate(tok[1], "yyyy-MM-dd");
tmpArray[cnt][2] = tok[2];
tmpArray[cnt][3] = tok[3];
tmpArray[cnt][4] = Integer.valueOf(tok[4]);
cnt++;
}
}
// Close the BufferReader
br.close();
}
// Trap IO Exceptions from the Bufferreader if any...
catch (IOException ex) {
System.out.println("\n\u001B[31mThe supplied Translation Table file could"
+ " not be found!\n\u001B[39;49m" + filePath);
}
// Return filled 2D Object Array
return tmpArray;
}
注意上述代码中的行: tmpArray [cnt] [1] = CDate(tok [1],“YYYY-MM-dd”); 。此行包含另一种将日期字符串转换为Date数据类型的自定义方法。以下是 cDate()方法的代码:
private static Date cDate(String val, String... expectedFormat) {
//Usage: Date d = cDate("2016-06-22", "yyyy-MM-dd");
String dFormat = "dd/MM/yyyy";
if (expectedFormat.length != 0) { dFormat = expectedFormat[0]; }
SimpleDateFormat formatter = new SimpleDateFormat(dFormat, Locale.ENGLISH);
try {
Date bdate = formatter.parse(val);
return bdate; // Default format is 01/01/2015
}
catch (ParseException e) { return null; }
}
希望这可以帮助你(和其他人)。