0

i'm trying to replace some letters in txt file and rewrite it but i can't keep indents at all. Source file looks like this :

aaaaaaaaaWRPaaaaaaaa

bbbWRPbbbbbbbbbbbbbb

here's what i've tried :

public static  void fileReader (String path) throws FileNotFoundException, IOException {
    File prevfile = new File(path);
    BufferedReader reader = new BufferedReader(new FileReader(prevfile));
    String line = reader.readLine();
    while (line!=null){
        content = content  + line + "\n" ;
        line = reader.readLine();
    }
    String newCOntent = content.replaceAll("WRP","WRD");
    FileWriter writer = new FileWriter(prevfile);
    writer.write(newContent);

    writer.close();
    reader.close();

}

}

after which i get output in a single line.

Vadim Popov
  • 49
  • 1
  • 8
  • 1
    Are you on Windows? Chances are that the original file uses CRLF line endings, but you only write LF ones. See [this blog post](https://www.baeldung.com/java-string-newline) for details. – Joachim Sauer Oct 17 '19 at 11:06
  • 2
    Try `content = content + line + System.lineSeparator()`... It may work, but I really advice you to have a look at `java.nio` which lets you read and write lines using a `List` where each `String` is a line. That way. you wouldn't have to care at all... – deHaar Oct 17 '19 at 11:06
  • OR don't use `content = content + line + "\n" ;` at all. This is very inefficient for larger files because it would give you O(n^2) complexity. Instead read files using built-in tools provided by Java: [How do I create a Java string from the contents of a file?](https://stackoverflow.com/q/326390) (see accepted answer there). – Pshemo Oct 17 '19 at 11:09
  • 1
    Also `replaceAll` uses regex syntax, so if one of characters you would like to change would be one of regex metacharacters like `*` `+` `?` `[` etc. you would not get expected results. Instead use `replace(...)` which also replaces ALL occurrences of described string but doesn't support regex syntax. – Pshemo Oct 17 '19 at 11:12
  • @JoachimSauer i didn't know about difference in line endings, that helped thanks a lot! – Vadim Popov Oct 17 '19 at 11:43
  • @JoachimSauer I guess using CRLF or just LF won’t be the best option if I want my code to work on different OS? – Vadim Popov Oct 17 '19 at 14:36
  • @VadimPopov: the savest cross-OS bet is probably to read the line-ending without modifying it and write it back as it was. That means you must not use `readLine()`, but something like `read(char[])` instead. – Joachim Sauer Oct 17 '19 at 17:29

0 Answers0