Advertisement
brilliant_moves

Writer.java

Feb 6th, 2015
537
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.08 KB | None | 0 0
  1. import java.util.Scanner;
  2. import java.io.File;
  3. import java.io.FileWriter;
  4. import java.io.BufferedWriter;
  5.  
  6. public class Writer {
  7.  
  8.     /**
  9.     *   Read text file, for each line remove leading spaces and replace them with a count
  10.     *   of the number of spaces.  Requires a text file "Squeeze.txt".
  11.     */
  12.  
  13.     public static void main(String args[]) {
  14.         String theText = "";
  15.         String line;
  16.         int c;
  17.         try {
  18.             Scanner in = new Scanner(new File("Squeeze.txt"));
  19.             while (in.hasNextLine()) {
  20.                 line = in.nextLine();
  21.                 c=0;
  22.                 while (line.startsWith(" ")) {
  23.                     line = line.substring(1, line.length());
  24.                     c++;
  25.                 } // while line
  26.                 if (c>0) {
  27.                     theText += c;
  28.                 } // if
  29.                 theText += line + "\r\n";
  30.             } // while in
  31.         }
  32.         catch(Exception e) {
  33.             System.out.println("Error: " + e.getMessage());
  34.         } // try/catch
  35.  
  36.         try {
  37.             BufferedWriter bw = new BufferedWriter(new FileWriter(new File("Squeeze2.txt")));
  38.             bw.write(theText);
  39.             bw.close();
  40.         }
  41.         catch (Exception e) {
  42.             System.out.println("Couldn't write to file!");
  43.         } // try/catch
  44.  
  45.     } // main()
  46.  
  47. } // class Writer
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement