我在我的想法中有一個結...我將int 0寫入文件三次,每個文件後跟行結束符(我有試過\ n(0x0A)和\ r(0x0D))。這裏是文件的字節readline忽略文件中的 n或 r(文本與二進制文件)
00 00 00 00 0D 00 00 00 00 0D 00 00 00 00 0D
的內容早在讀它,我裹
FileInputStream is = new FileInputStream(theFile);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
然而,我到
String s = br.readLine();
第一次調用讀取的文件(15位),而不是在位置5(即0X0D),因爲我本來希望停止的結束。任何人看到我誤解了事情的工作方式?多謝。基於下面的評論
新增信息:代碼
public class TestApp4 {
public static void main(String args[]) {
try {
File theFile = new File("Test.dat");
FileInputStream is = new FileInputStream(theFile);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
System.out.println("input stream position: " + is.getChannel().position());
String s = br.readLine();
byte[] bs = s.getBytes();
int i = ByteBuffer.wrap(bs).getInt();
System.out.println("input stream position: " + is.getChannel().position());
System.out.println("line: " + i);
s = br.readLine();
System.out.println("line: ");
s = br.readLine();
System.out.println("line: ");
br.close();
} catch (Throwable e) { e.printStackTrace(); }
}
}
輸出從我這得到的是
input stream position: 0
input stream position: 15
line: 0
line:
line:
,我看到我錯在哪裏。每個
br.readLine();
打破它應該在哪裏。我的困惑源於這樣的事實:
is.getChannel().position()
高級到文件末尾而不是行尾。我誤解了這個值代表了讀入字符串的最後一個位置 - 這顯然是不正確的。看起來像這是讀入較大流的位置。感謝幫助理清我的booboo。
你究竟是什麼意思「讀到文件末尾「?你是否暗示'readLine'返回完整的String而不是單行? – Lothar
是什麼讓你覺得它不會停在行尾?不知道你爲什麼要將二進制數據讀入一個字符串,但我只是試過,它只讀取第一行。請張貼更多你的代碼。 – Oleg