title: Reformatting source code with Text I/O
body: <p>I am teaching myself programming with Java through a textbook.  An exercise asks you to write a program that reformats an entire source code file (using the command line):</p>
  
  <p>from this format (next-line brace style):</p>
  
  <pre><code>public class Test
  {
      public static void main(String[] args)
      {
      // Some statements
      }
  }
  </code></pre>
  
  <p>to this format (end-of-line brace style):</p>
  
  <pre><code>public class Test {
      public static void main(String[] args) {
      // Some statements
      }
  }
  </code></pre>
  
  <p>Here's the code I have so far:</p>
  
  <pre><code>import java.io.*;
  import java.util.*;
  
  public class FOURTEENpoint12 {
  
  public static void main(String[] args) throws IOException {
  
      if (args.length != 2) {
          System.out.println
                      ("Usage: java FOURTEENpoint12 sourceFile targetFile");
          System.exit(1);
      }
  
      File sourceFile = new File(args[0]);
      File targetFile = new File(args[1]);
  
      if (!sourceFile.exists()) {
          System.out.println("File does not exist");
          System.exit(2);
      }
  
      Scanner input = new Scanner(sourceFile);
      PrintWriter output = new PrintWriter(targetFile);
  
      String token;
  
  
      while (input.hasNext()) {
          token = input.next();
          if (token.equals("{"))
              output.println("\n{\n");
          else
              output.print(token + " ");
  
      }
  
      input.close();
      output.close();
  }
  </code></pre>
  
  <p>}</p>
  
  <p>I have two problems:</p>
  
  <ol>
  <li><p>I have tried many different while blocks, but can't get anything close to what the book is asking.  I've tried different combinations of regular expressions, delimeters, token arrays, but still way off.</p></li>
  <li><p>The book asks you to reformat a single file, but the chapter never explained how to do that.  It only explains how to rewrite the text into a new file.  So I just wrote the program to create a new file.  But I would really like to do it the way the problem asks.</p></li>
  </ol>
  
  <p>If someone could help me with these two problems, it would actually solve many of the problems I'm having with alot of the exercises.  Thanks in advance.</p>