請您指出我的代碼中的錯誤在哪裏?J2ME將文本文件讀入字符串數組
我有一個具有以下數據結構的簡單的文本文件:
something1
something2
something3
...
它導致一個String[]
,每一個元素是文件的最後一個元素。我找不到這個錯誤,但是在line.setLength(0);
有什麼想法嗎?
public String[] readText() throws IOException {
InputStream file = getClass().getResourceAsStream("/questions.txt");
DataInputStream in = new DataInputStream(file);
StringBuffer line = new StringBuffer();
Vector lines = new Vector();
int c;
try {
while((c = in.read()) != -1) {
if ((char)c == '\n') {
if (line.length() > 0) {
// debug
//System.out.println(line.toString());
lines.addElement(line);
line.setLength(0);
}
}
else{
line.append((char)c);
}
}
if(line.length() > 0){
lines.addElement(line);
line.setLength(0);
}
String[] splitArray = new String[lines.size()];
for (int i = 0; i < splitArray.length; i++) {
splitArray[i] = lines.elementAt(i).toString();
}
return splitArray;
} catch(Exception e) {
System.out.println(e.getMessage());
return null;
} finally {
in.close();
}
}
非常好,非常感謝! – farkasseb