Search code examples
javastringfilecurly-braces

Reformatting Java Source Code, instead of next line use end of line curly braces


I've been trying to figure out how to implement a problem (linked further down) but, I'm hitting a wall.

Basically I have to reformat source code that uses next line curly braces to end of line curly braces. For some reason, the professor for my class decided to assign this problem in our Strings chapter and not in the Text I/O chapter (which is about 5 chapters later).

String sourceString = new String(Files.readAllBytes(Paths.get("Test.txt")));
String formatted = sourceString.replaceAll("\\s\\{", "\\{");
System.out.println(formatted);

So that's what I have so far. When I do a run, the output is the same as the source file. I followed this problem and using an idiom I found to convert all of the file into a String, the replaceAll method stopped... replacing.

While I still had it set up like this

StringBuilder source = new StringBuilder();
    while(s.hasNext()){
        source.append(s.nextLine());
    }
    String sourceString = source.toString();
    String formatted = sourceString.replaceAll("\\)\\s*\\{", ") {");
    System.out.println(formatted);

the output is all on a single line. I feel like the replaceAll method isn't occurring at all. I feel like I'm forgetting something blatantly obvious.


Solution

  • The second argument of replaceAll() is a String, not a regex, so no need to escape the { there.

    Also add a + to denote one or more whitespaces.

    So:

    sourceString.replaceAll("\\s+\\{", "{")