BufferedReader.skip() 相当于行,而不是字符
BufferedReader.skip() equivalent for lines, not characters
在 Java 中是否有某种等同于 BufferedReader.skip() 的东西,它将行数而不是字符数作为参数?
我想跳转到文本文件中的特定行并从该点开始读取,而无需遍历文件的所有行并检查行号(数万行 - 模型 obj 文件).
我看到的所有例子都在处理行号的检查,这不是我想要的。
所以,解决方案是使用FileInputStream.skip()
。
更新: 在每行迭代中手动添加 system-specific 新行分隔符字节长度到行字节长度解决了错误字节跳过的问题,所以现在它终于按预期工作了!
定义一些 Long
变量,您将在其中存储要跳过的字节数。我在我的主应用程序中做到了 class (App.class):
public static long lineByteOffset = 0;
然后,在你的 method/function 中,你用 BufferedReder
阅读你的行,像这样(我从中读取的所有文件都编码为 UTF-8):
File objFile = new File(PATH_TO_YOUR_FILE_HERE);
FileInputStream fir = null;
try {
fir = new FileInputStream(objFile);
} catch (FileNotFoundException e) {
System.err.println("File not found!");
}
fir.skip(App.lineByteOffset);//<--- 1ST IMPORTANT PART: SET HOW MANY BYTES TO SKIP, YOU START WITH 0 FOR THE 1ST TIME
BufferedReader reader = new BufferedReader(new InputStreamReader(fir, "UTF-8"));
int nls = System.getProperty("line.separator").getBytes().length;
String line;
try {
while ((line = reader.readLine()) != null) {
App.lineByteOffset += (long) (line.getBytes().length + nls);//<--- 2ND IMPORTANT PART: INCREASE NUMBER OF BYTES TO SKIP FOR NEXT TIME
/*
DO YOUR STUFF HERE...
IN MY CASE IT RETURNS SPECIFIC BLOCK
WHICH IN EFFECT EXIT THE WHILE LOOP AS NEEDED
SO THAT THE NEXT TIME IT CONTINUE WHERE WE LEFT IT
WITHOUT NEED TO READ THE WHOLE FILE FROM THE START ONCE AGAIN
*/
}
reader.close();
} catch (IOException e) {
System.err.println("Error reading the file");
}
在 Java 中是否有某种等同于 BufferedReader.skip() 的东西,它将行数而不是字符数作为参数?
我想跳转到文本文件中的特定行并从该点开始读取,而无需遍历文件的所有行并检查行号(数万行 - 模型 obj 文件).
我看到的所有例子都在处理行号的检查,这不是我想要的。
所以,解决方案是使用FileInputStream.skip()
。
更新: 在每行迭代中手动添加 system-specific 新行分隔符字节长度到行字节长度解决了错误字节跳过的问题,所以现在它终于按预期工作了!
定义一些 Long
变量,您将在其中存储要跳过的字节数。我在我的主应用程序中做到了 class (App.class):
public static long lineByteOffset = 0;
然后,在你的 method/function 中,你用 BufferedReder
阅读你的行,像这样(我从中读取的所有文件都编码为 UTF-8):
File objFile = new File(PATH_TO_YOUR_FILE_HERE);
FileInputStream fir = null;
try {
fir = new FileInputStream(objFile);
} catch (FileNotFoundException e) {
System.err.println("File not found!");
}
fir.skip(App.lineByteOffset);//<--- 1ST IMPORTANT PART: SET HOW MANY BYTES TO SKIP, YOU START WITH 0 FOR THE 1ST TIME
BufferedReader reader = new BufferedReader(new InputStreamReader(fir, "UTF-8"));
int nls = System.getProperty("line.separator").getBytes().length;
String line;
try {
while ((line = reader.readLine()) != null) {
App.lineByteOffset += (long) (line.getBytes().length + nls);//<--- 2ND IMPORTANT PART: INCREASE NUMBER OF BYTES TO SKIP FOR NEXT TIME
/*
DO YOUR STUFF HERE...
IN MY CASE IT RETURNS SPECIFIC BLOCK
WHICH IN EFFECT EXIT THE WHILE LOOP AS NEEDED
SO THAT THE NEXT TIME IT CONTINUE WHERE WE LEFT IT
WITHOUT NEED TO READ THE WHOLE FILE FROM THE START ONCE AGAIN
*/
}
reader.close();
} catch (IOException e) {
System.err.println("Error reading the file");
}