Search code examples
javastringfilestringbuffer

How to replace specific String in a text file by java?


I'm writing a program with a text file in java, what I need to do is to modify the specific string in the file. For example, the file has a line(the file contains many lines)like "username,password,e,d,b,c,a" And I want to modify it to "username,password,f,e,d,b,c" I have searched much but found nothing. How to deal with that?


Solution

  • In general you can do it in 3 steps:

    1. Read file and store it in String
    2. Change the String as you need (your "username,password..." modification)
    3. Write the String to a file

    You can search for instruction of every step at Stackoverflow.

    Here is a possible solution working directly on the Stream:

    public static void main(String[] args) throws IOException {
    
        String inputFile = "C:\\Users\\geheim\\Desktop\\lines.txt";
        String outputFile = "C:\\Users\\geheim\\Desktop\\lines_new.txt";
    
        try (Stream<String> stream = Files.lines(Paths.get(inputFile));
                FileOutputStream fop = new FileOutputStream(new File(outputFile))) {
            stream.map(line -> line += " manipulate line as required\n").forEach(line -> {
                try {
                    fop.write(line.getBytes());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }
    }