我每天收到一个文件:
问题:文件的列顺序会定期更改
目标:打印lastName,firstName,地址的列数据,无论列顺序如何
我一直在使用以下代码并手动更改数据值以匹配列。
testfile1.txt
1st day file format
ID lastName address phone firstName
45 Gates 111 some lane 777-888-9999 Bill
2nd day file format
address ID phone firstName lastName
111 some lane 81 444-555-1111 John Doe
-
import java.io.BufferedReader;
import java.io.FileReader;
public class test2 {
public static void main(String args[]) throws Exception {
String dataFileName = "C:/testfiles/testfile1.txt";
String line;
int lineNumber = 0;
BufferedReader bReader = new BufferedReader(new FileReader(dataFileName));
bReader.readLine();
while ((line = bReader.readLine()) != null) {
lineNumber++;
String datavalue[] = line.split("\t");
String lastName = datavalue[1];
String firstName = datavalue[5];
String address = datavalue[3];
System.out.println(lastName + "'" + firstName + "," + address);
}
}
}
答案 0 :(得分:1)
我认为您可以尝试下面的内容 -
import java.io.BufferedReader;
import java.io.FileReader;
public class test2 {
public static void main(String args[]) throws Exception {
String dataFileName = "C:/testfiles/testfile1.txt";
String line;
boolean isFirstColumn = true;
BufferedReader bReader = new BufferedReader(new FileReader(dataFileName));
int[] order_Fname_Lname_Address = new int[3];
while ((line = bReader.readLine()) != null) {
String datavalue[] = line.split("\t");
if(isFirstColumn) {
for (int i = 0; i < datavalue.length; i++) {
switch (datavalue[i]) {
case "firstName":
order_Fname_Lname_Address[0] = i;
break;
case "lastName":
order_Fname_Lname_Address[1] = i;
break;
case "address":
order_Fname_Lname_Address[2] = i;
break;
}
}
isFirstColumn = false;
continue;
}
String firstName = datavalue[order_Fname_Lname_Address[0]];
String lastName = datavalue[order_Fname_Lname_Address[1]];
String address = datavalue[order_Fname_Lname_Address[2]];
System.out.println(lastName + " " + firstName + "," + address);
}
bReader.close();
}
}
答案 1 :(得分:1)
这是第一种方法。我会以某种方式尝试这样:
int colLastName, colFirstName, colAddress;
line = bReader.readLine();
String columnOrder []= line.split("\t");
for (int i=0; i< columnOrder.length; i++){
if (columnOrder[i].equals("lastName")){
colLastName = i;
}
else if (columnOrder[i].equals("firstName"){
colFirstName = i;
}
else if (columnOrder[i].equals("address"){
colAddress = i;
}
}
while ((line = bReader.readLine()) != null) {
lineNumber++;
String datavalue[] = line.split("\t");
String lastName = datavalue[colLastName];
String firstName = datavalue[colFirstName];
String address = datavalue[colAddress];
System.out.println(lastName + "'" + firstName + "," + address);
}