How Can I Reset The File Pointer to the Beginning of the File in Java?

前端 未结 10 1447
孤城傲影
孤城傲影 2021-02-19 20:17

I am writing a program in Java that requires me to compare the data in 2 files. I have to check each line from file 1 against each line of file 2 and if I find a match write the

10条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-19 20:51

    If you can clearly indentify the dimension of your file you can use mark(int readAheadLimit) and reset() from the class BufferedReader. The method mark(int readAhedLimit) add a marker to the current position of your BufferedReader and you can go back to the marker using reset().

    Using them you have to be careful to the number of characters to read until the reset(), you have to specify them as the argument of the function mark(int readAhedLimit).

    Assuming a limit of 100 characters your code should look like:

    class MyFileReader {
        BufferedReader data;
        int maxNumberOfCharacters = 100;
    
        public MyFileReader(String fileName)
        {
            try{
                FileInputStream fstream = new FileInputStream(fileName);
                data = new BufferedReader(new InputStreamReader(fstream));
                //mark the current position, in this case the beginning of the file
                data.mark(maxNumberOfCharacters);
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        public void resetFile(){
            data.reset();
        }
    
        public void closeFile()
        {
            try{
                in.close();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

提交回复
热议问题