Read Data File address (Java)

2019-09-16 16:57发布

I have this code for reading data and works fine but I want to change the start point that the data is read from - My DataFile.txt is "abcdefghi" and the output is

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

I want to start at the second byte so the output would be

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

Code:

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());
        }
    }    
}

标签: java file
1条回答
姐就是有狂的资本
2楼-- · 2019-09-16 17:28

You can simple ignore the first n bytes as follows.

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);
}

Edit: If you want to access a random location in file, then you need to use RandomAccessFile. See this for detailed examples.

Related SO post:

查看更多
登录 后发表回答