Inserting text in middle using RandomAccessFile removes some text after that

前端 未结 5 2080
攒了一身酷
攒了一身酷 2020-12-12 02:20

My Sample Code

    String line = null;
    RandomAccessFile file = new RandomAccessFile(\"D:/mahtew.txt\", \"rw\");
    System.out.println(file.getFilePointe         


        
5条回答
  •  鱼传尺愫
    2020-12-12 02:49

    Understand that when you write with a RAF, you over-write data which was previously held at the file pointer location. If you want to insert text into a file, I suggest that you not use a RAF but rather simply read the text of the file into a String or ArrayList or StringBuilder, using a File held by a FileReader wrapped in a BufferedReader or a File wrapped in a Scanner, alter the Strings or StringBuilder held in memory, and then write the altered data to the new file using a FileWriter wrapped in a PrintWriter.

    e.g.,

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.PrintWriter;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Scanner;
    
    public class AppendLine {
       private static final String FILE_PATH = "src/tetris/mahtew.txt";
       private static final String MARKER_LINE = "Text to be appended with";
       private static final String TEXT_TO_ADD = "new text has been appended";
    
       public static void main(String[] args) {
          List fileLines = new ArrayList();
          Scanner scanner = null;
          try {
             scanner = new Scanner(new File(FILE_PATH));
             while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                fileLines.add(line);
                if (line.trim().equalsIgnoreCase(MARKER_LINE)) {
                   fileLines.add(TEXT_TO_ADD);
                }
             }
    
          } catch (FileNotFoundException e) {
             e.printStackTrace();
          } finally {
             if (scanner != null) {
                scanner.close();
             }
          }
    
          PrintWriter pw = null;
          try {
             pw = new PrintWriter(new File(FILE_PATH));
             for (String line : fileLines) {
                pw.println(line);
             }
          } catch (FileNotFoundException e) {
             e.printStackTrace();
          } finally {
             if (pw != null) {
                pw.close();
             }
          }
       }
    }
    

提交回复
热议问题