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.

  • What do you really want is to simply interact with text file or you need indeed to interact with a desktop application? Aug 7, 2019 at 7:26
  • Selenium can only automate a browser it cannot interact with a notepad file. You need to use other Classes and packages in java. what all have you tried, paste your code. Some amount of "Research" is expected before you ask a question on this forum. Go through the Help Secion and how to ask a good question
    – Alok
    Aug 9, 2019 at 14:06

1 Answer 1


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) {
        } while (line != null);
    } 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
    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) {

    } 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);

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.