如何选择性地将文件扫描成两个2d字符串数组?
我有一个看起来像这样的文件:
2014 fruit apple red 50 30
2015 vegetable spinach green 10
2014 fruit orange orange 100
2014 fruit banana yellow 90 100
2015 vegetable corn yellow 120
我正在尝试读取文件,并将每一行放入2d字符串数组(由空格分隔)。我想要一个仅由2014年开始的行组成的数组,以及另一个由2015年开始的行形成的数组。
因为它是针对一个类的,所以我坚持使用严格的参数:1.它必须来自文本文件,并且2.必须进入两个2d数组。
我能够将整个文件成功读取到一个2d String数组中,但是我为两个数组尝试的所有操作似乎都失败了。这就是我得到的...成功的单个2d数组:
public static void main(String[] args) throws Exception {
//Initializes the variables needed to read the line length of the file
FileReader fr = null;
LineNumberReader lnr = null;
File newFile = new File("ProjectTest.txt");
//Initiallizes the variables needed to create the 2D array
BufferedReader inputStream = new BufferedReader(new FileReader(newFile));
Scanner scannerIn = new Scanner(inputStream);
//Other variables
int lineNum = 0;
int linesCounter = 0;
String str;
//Determines how many lines in the file
try {
fr = new FileReader(newFile);
lnr = new LineNumberReader(fr);
while (lnr.readLine() != null) {
lineNum++;
}
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
if (fr != null) {
fr.close();
}
if (lnr != null) {
lnr.close();
}
}
//Create the 2D array
String arrayA[][] = new String[lineNum][];
while (scannerIn.hasNextLine() && linesCounter < lineNum) {
arrayA[linesCounter] = scannerIn.nextLine().split("\\s");
linesCounter++;
}
//Test-print the array
for (int i = 0; i< lineNum; i++){
System.out.println(arrayA[i][2]);
}
}
我尝试了许多不同的方法来尝试将这些数据分成两个阵列,但是我认为我的困惑来自于何时以及如何使用扫描器与缓冲读取器。我尝试过if / then语句,仅将2014行读入一个数组,并且尝试将一个数组复制到另一个数组。不用说,我把它们都弄错了。这是使用if / then语句对两个2d数组进行的多次尝试之一:
String arrayA[][] = new String[lineNum][];
String arrayB[][] = new String[lineNum][];
String line = inputStream.readLine();
while (line != null) {
if (line.contains("2014")){
arrayA[linesCounter] = inputStream.readLine().split("\\s");
linesCounter++;
} else {
arrayB[linesCounter] = inputStream.readLine().split("\\s");
linesCounter++;
}
}
请帮我!!我感谢你们!
这是一种实现方法:
String[][] arrayA = new String[lineNum][];
String[][[ arrayB = new String[lineNum][];
int counterA = 0;
int counterB = 0;
while (scannerIn.hasNextLine()) {
String line = scannerIn.nextLine();
String[] parts = line.split("\\s");
if (line.startsWith("2014")) {
arrayA[counterA++] = parts;
} else if (line.startsWith("2015")) {
arrayB[counterB++] = parts;
}
}
// prune excess elements
arrayA = Arrays.copyOf(arrayA, counterA);
arrayB = Arrays.copyOf(arrayB, counterB);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句