How to add and remove line from notepad file using selenium



  • Need code to add and remove lines from notepad file using selenium in java. I have to do some more operations on notepad but add and remove will be helpful.



  • Check this working code.

    To add line in notepad or text file.

    Step 1: Read existing data from notepad in list.

    public static List<String> readTextFile(String filePath) throws IOException {
        // use BufferedReader to read notepad file line by line
        FileReader fReader = null;
        BufferedReader bfrReader = null;
        // Store lines in a
        List<String> lines = new ArrayList<>();
        File fp = new File(filePath);
        if (fp.exists()) {
            fReader = new FileReader(fp);
            bfrReader = new BufferedReader(fReader);
            String line = null;
            do {
                // Read one line and store it in String variable
                line = bfrReader.readLine();
                if (line != null) {
                    lines.add(line);
                }
            } while (line != null);
            bfrReader.close();
            fReader.close();
        } else {
            System.out.println("File does not exist");
        }
        return lines;
    }
    

    Step 2: Add new line to the list, you want to append in java file.

    Here we used above function to read existing file before appending new line.

    public static void appendLine(String filePath, String line) throws IOException {
        // read old notepad file and store lines
        List<String> lines = readTextFile(filePath);
        // add new line to the list
        lines.add(line);
        FileWriter fWriter;
        BufferedWriter bWriter;
        File fp = new File(filePath);
        if (fp.exists()) {
            fWriter = new FileWriter(fp);
            bWriter = new BufferedWriter(fWriter);
            // write to notepad file
            for (String oneLine : lines) {
                bWriter.append(oneLine);
                bWriter.newLine();
            }
            bWriter.close();
            fWriter.close();
    
        } else {
            System.out.println("File does not exist");
        }
    }
    

    To replace string or Regrex

        public static void replaceRegrex(File fSrc, String regrex, String strReplace) throws IOException {
        String fSrcStr = new String(Files.readAllBytes(fSrc.toPath()));
        String fStr = fSrcStr.replaceAll(regrex, strReplace);
        FileWriter fileWriter = new FileWriter(fSrc);
        fileWriter.write(fStr);
        fileWriter.close();
    }
    

    For more notepad related operation refer below links which contain code having more details.

    1. Java class for append operation
    2. For other java operations on text file like appendLine, compareTextFiles, createTextFile, readTextFile, replaceRegrex, searchRegrex


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2