它看起來像你太頻繁地調用scan.nextLine()。每次調用scan.nextLine()時,它都會使掃描器前進到當前行。假設你的文件有100行,每行有6個「條目」(用「 - 」分隔),我會將test = scan.nextLine().split("-");
移動到while循環的末尾(但仍在循環中),以便每行調用一次。
編輯...
建議的解決方案: 鑑於該格式的文件,
abcxyz
abcxyz ...(共100次)
使用此代碼:
try{
File file = new File("testwrite.txt");
Scanner scan = new Scanner(file);
String[] test = scan.nextLine().split("-");
while(r<100){
while(c<6){
data[r][c] = test[c];
c++;
}
r++;
c = 0 ;
test = scan.nextLine().split("-");
}
System.out.println(data[1][5]);
}catch(Exception e){
System.out.println("Error: " + e.getMessage());
}
然後使用data [line] [index]來訪問您的數據。從其它的字符,除了 -
BufferedReader reader = new BufferedReader(new FileReader(path));
int lineNum = 0; //Use this to skip past a column header, remove if you don't have one
String readLine;
while ((readLine = reader.readLine()) != null) { //read until end of stream
if (lineNum == 0) {
lineNum++; //increment our line number so we start with our content at line 1.
continue;
}
String[] nextLine = readLine.split("\t");
for (int x = 0; x < nextLine.length; x++) {
nextLine[x] = nextLine[x].replace("\'", ""); //an example of using the line to do processing.
...additional file processing logic here...
}
}
再次,在我的情況,我對標籤(\ t)的分裂,但你可以很容易地在拆分:
System.out.println(data [1] [5]) - 僅用於測試目的。 –
看起來像'for'循環會更適合這個。 – arshajii
首先第8行, test = scan.nextLine()。split(「 - 」); Test是一個字符串數組,你需要指定一個索引。 – Waleed