Search code examples
javacharacterbufferedreaderbufferedwriter

Java: Overwrite one character while copying a textfile


My current program reads a file and copies it to another directory, but I want it to change one single character to x, which is given by two ints for the number of the line and the number of the character in the line. For example if int line = 5 and int char = 4, the fourth character in line five is changed to an x, the rest remains. How can I add this to my program?

import java.io.*;
import java.util.Scanner;

public class copytest {

    public static void main(String[] args) throws Exception {       
        readFile();
    }

    public static void readFile() throws Exception {

        // Location of file to read
        File file = new File("Old.txt");

        Scanner scanner = new Scanner(file);

        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            //System.out.println(line);
            writeFile(line);
        }
        scanner.close();
        System.out.println("File Copied"); 
    }

    public static void writeFile(String copyText) throws Exception {

        String newLine = System.getProperty("line.separator");

        // Location of file to output
        Writer output = null;
        File file = new File("New.txt");
        output = new BufferedWriter(new FileWriter(file, true));
        output.write(copyText);
        output.write(newLine);
        output.close();     
    }
 }

Solution

  • Change your loop to:

     int i=0;
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            if (i == lineNumber) {
                if (line.length() >= charNumber) {
                    line = line.substring(0,charNumber) + wantedChar +
                           line.substring(charNumber);
                }
            }
            writeFile(line);
            i++;
        }
    

    Note that it will replace the char only if the line long enogth.