java如何删除文件的前几行数据(不使用临时文件)

    private List readAndRemoveFirstLines(File file, int lineNum) throws IOException{ 
        List strList = new ArrayList();
        RandomAccessFile raf = null;
        try{
            raf = new RandomAccessFile(file, "rw");         
             //Initial write position                                             
            long writePosition = raf.getFilePointer();
            for (int i = 0 ; i < lineNum ; i++){
                String line = raf.readLine();
                if(line == null){
                    break;
                }
                strList.add(line);                     
            }
            // Shift the next lines upwards.                                      
            long readPosition = raf.getFilePointer();                             
    
            byte[] buff = new byte[1024];                                         
            int n;                                                                
            while (-1 != (n = raf.read(buff))) {                                  
                raf.seek(writePosition);                                          
                raf.write(buff, 0, n);                                            
                readPosition += n;                                                
                writePosition += n;                                               
                raf.seek(readPosition);                                           
            }                                                                     
            raf.setLength(writePosition);
        } catch(IOException e){
            LOG.error("readAndRemoveFirstLines error", e);
            throw e;
        } finally{
            try{
                if(raf != null){
                    raf.close();   
                }
            }catch(IOException e){
                LOG.error("close RandomAccessFile error", e);
                throw e;
            }
        }
        
        return strList;
    }         

你可能感兴趣的:(java)