Deleting the last line of a file with Java

后端 未结 2 905
粉色の甜心
粉色の甜心 2020-12-18 00:58

I have a .txt file, which I want to process in Java. I want to delete its last line.

I need ideas on how to achieve this without having to copy the enti

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-18 01:16

    By taking RandomAccessFile you can:

    • use method seek(long) to jump forward and read those lines. But you won't know exactly how big the jump should be.
    • to delete last lines you need the position of begin of last line so before reading each line store their file pointer position (method getFilePointer()). Deleting to that position you use setLength(long).

    Code would be something like this:

        LinkedList lines=null;
        int howMuch = 1; // one line to read and delete
        try{
            RandomAccessFile raf = new RandomAccessFile(inputFileName, "rw");
    
            System.out.println("File Length="+raf.length());
    
            long step = 20;  // here I advice to write average length of line
            long jump = raf.length()();
            LinkedList pos = new LinkedList();
    
            Entry,LinkedList> rLinesRead = getRemainingLines(raf,
                    new AbstractMap.SimpleEntry,LinkedList> (lines,pos));
            while(rLinesRead.getKey().size(),LinkedList> getRemainingLines(RandomAccessFile raf,
            Entry,LinkedList> linesAlreadyLoadedFromEnd) throws IOException{
        LinkedList pLines = linesAlreadyLoadedFromEnd.getKey();
        LinkedList pPos = linesAlreadyLoadedFromEnd.getValue();
    
        long init=raf.getFilePointer();
        String str = raf.readLine();
        if(pPos.size()>0?pPos.getFirst()==0:false || str==null)
            return linesAlreadyLoadedFromEnd;
    
        LinkedList lines = new LinkedList();
        LinkedList pos = new LinkedList();
        if(init==0L ){              
            lines.add(str);
            pos.add(0L);
        }
        Long tmpPos = raf.getFilePointer();
        while ((str = raf.readLine())!=null && !pPos.contains(tmpPos)){
            lines.add(str);
            pos.add(tmpPos);
            tmpPos = raf.getFilePointer();
        }
        pLines.addAll(0,lines);
        pPos.addAll(0,pos);
        return new AbstractMap.SimpleEntry,LinkedList> (pLines,pPos);
    }
    

提交回复
热议问题