我已經讀取了一個文件到一個數組中,但是想知道如何解析該數組中的某些值。Java Array解析
我的代碼:
...
try{
...
String strLine;
String delims= "[ ]+";
//parsing it
ArrayList parsedit = new ArrayList();
while((strLine=br.readLine())!=null){
System.out.println("Being read:");
System.out.println(strLine);
parsedit.add(strLine.split(delims));
}
System.out.println("Length:" + parsedit.size());
in.close();
...
,我讀的文件是這樣的:
a b c d e f g
1 2 3 4 5 6 7
1 4 5 6 3 5 7
1 4 6 7 3 2 5
這使得像這樣的輸出:
How many files will be input? 1
Hey, please write the full path of the input file number1!
/home/User/Da/HA/file.doc
Being read:
a b c d e f g
Being read:
1 2 3 4 5 6 7
...
Length:4
我想解析出這些數據,並且只剩下第一個和第五個值,以便它可以像這樣讀取:
a e
1 5
有沒有人有關於如何去做的建議? 編輯: 繼一些我已經改變了我的代碼的建議:
public static void main(String[] args) {
System.out.print("How many files will be input? ");
Scanner readIn=new Scanner(System.in);
int input=readIn.nextInt();
int i=1;
while(i<=input){
System.out.println("Hey, please write the full path of the input file number" + i + "! ");
Scanner fIn=new Scanner(System.in);
String fileinput=fIn.nextLine();
try{
FileInputStream fstream=new FileInputStream(fileinput);
DataInputStream in=new DataInputStream(fstream);
BufferedReader br=new BufferedReader(new InputStreamReader(in));
String strLine;
String delims= "[ ]+";
ArrayList parsedit = new ArrayList();
while((strLine=br.readLine())!=null){
System.out.println("Being read:");
System.out.println(strLine);
parsedit.add(strLine.split(delims));
}
String[] splits=strLine.split(delims);
System.out.println("Length:" + splits.length);
in.close();
}
catch(Exception e){
System.err.println("Error: " + e.getMessage());
}
i++;
}
}
}
這不給回任何錯誤,但它似乎並沒有被工作都是一樣的。我錯過了一些愚蠢的東西嗎?輸出是這樣的:
How many files will be input? 1
Hey, please write the full path of the input file number1!
/home/User/Da/HA/file.doc
Being read:
a b c d e f g
Being read:
1 2 3 4 5 6 7
...
但儘管我有一條線,告訴我數組的長度,它永遠不會被打印出來,這告訴我,我剛剛結束了打破超過我固定的。你知道我可能會遺漏/忘記什麼嗎?
除了'BufferedReader.readLine()',你可以嘗試使用'BufferedReader.read()'逐個字符地讀取字符以找到你要找的東西。 – Shaded
請不要使用DataInputStream來讀取文本http://vanillajava.blogspot.co.uk/2012/08/java-memes-which-refuse-to-die.html它比有用的更混亂。 –
@PeterLawrey你會推薦什麼? – Stephopolis