我具有用于读取数据的这段代码,并且可以正常工作,但是我想更改从中读取数据的起点-我的DataFile.txt是“ abcdefghi”
输出是

1)97
2)98
3)99
4)100


我想从第二个字节开始,所以输出将是

1)98
2)99
3)100
4)etc


码:

import java.io.*;
public class ReadFileDemo3 {
    public static void main(String[] args)throws IOException  {
        MASTER MASTER = new MASTER();
        MASTER.PART1();
    }
}

class MASTER {
    void PART1() throws IOException{
        System.out.println("OK START THIS PROGRAM");
        File file = new File("D://DataFile.txt");
        BufferedInputStream HH = null;
        int B = 0;
        HH = new BufferedInputStream(new FileInputStream(file));
        for (int i=0; i<4; i++) {
            B = B + 1;
            System.out.println(B+")"+HH.read());
        }
    }
}

最佳答案

您可以如下简单地忽略前n个字节。

HH = new BufferedInputStream(new FileInputStream(file));
int B = 0;
int n = 1; // number of bytes to ignore

while(HH.available()>0) {
    // read the byte and convert the integer to character
    char c = (char)HH.read();
    if(B<n){
        continue;
    }
    B++;
    System.out.println(B + ")" + (int)c);
}




编辑:如果要访问文件中的随机位置,则需要使用RandomAccessFile。有关详细示例,请参见this

相关SO帖子:


How do I fetch specific bytes from a file knowing the offset and length?
How to read a file from a certain offset

09-05 19:59