如果該文件是有效的UTF-8,也就是頁面由U + 00FF,又名(焦炭)0xFF的分裂,又名 「\ u00ff」 可以,'ÿ'
,然後緩衝讀者可以做。如果它是一個字節0xFF,則會出現問題,因爲UTF-8可能使用字節0xFF。
int soughtPageno = ...; // Counted from 0
int currentPageno = 0;
try (BufferedReader in = new BufferedReader(new InputStreamReader(
new FileInputStream(fileDir), StandardCharsets.UTF_8))) {
String str;
while ((str = in.readLine()) != null && currentPageno <= soughtPageno) {
for (int pos = str.indexOf('\u00FF'; pos >= 0;)) {
if (currentPageno == soughtPageno) {
System.out.println(str.substring(0, pos);
++currentPageno;
break;
}
++currentPageno;
str = str.substring(pos + 1);
}
if (currentPageno == soughtPageno) {
System.out.println(str);
}
}
}
對於一個字節0xFF的(錯誤的,遭到黑客攻擊UTF-8)使用的FileInputStream和讀取器之間的纏繞的InputStream:
class PageInputStream implements InputStream {
InputStream in;
int pageno = 0;
boolean eof = false;
PageInputSTream(InputStream in, int pageno) {
this.in = in;
this.pageno = pageno;
}
int read() throws IOException {
if (eof) {
return -1;
}
while (pageno > 0) {
int c = in.read();
if (c == 0xFF) {
--pageno;
} else if (c == -1) {
eof = true;
in.close();
return -1;
}
}
int c = in.read();
if (c == 0xFF) {
c = -1;
eof = true;
in.close();
}
return c;
}
以此爲一個例子,更多的工作要做。
使用'掃描儀'並將'delimiter'設置爲'\ u000C'。 –
感謝鮑里斯。我如何讓Scanner讀取utf-8文件?我認爲唯一的方法是使用InputStreamReader? – Steve