Search code examples
javabufferedreaderreadlinereplaceall

File input, String manipulation and output


I am trying to take a file (e.g a txt file of code) that hasn't been formatted properly and then format it by pushing the brackets into the correct place using 'tab'. But with my code it doesn't print the first bracket. Note the first and last bracket must remain untouched. Thanks

  @SuppressWarnings("unused")
  public static void main(String[] args) throws Exception {
    BufferedReader br = new BufferedReader(new FileReader("NewStripped.txt"));
    PrintWriter pw = new PrintWriter(new FileWriter("FinalStripped.txt"));
    String line; 
    int count = 0;
    try{
      while ((line = br.readLine()) != null) {
        count++;
        if (line != null){
          line = line.replaceAll("\\{", "\t{");
        } else if(line.contains("}")) {
          line = line.replaceAll("}","\t}");
        }                                       
        pw.println(line);
        System.out.println(line);
      }
      pw.close();
    } catch(Exception e) {
      e.printStackTrace();          
    }
  }
}

Solution

  • Count the depth level.

    int count = -1;
    ...
    while ((line = br.readLine()) != null) {
        if(line.contains("{")){
            count++;
            for(int i = 0; i < count; i++)
                 line = line.replaceAll("\\{", "\t\\{");
        } else if(line.contains("}")) {
            for(int i = 0; i < count; i++)
                 line = line.replaceAll("\\}","\t\\}");
            count--;
        }                                       
        pw.println(line);
        System.out.println(line);
    }