Search code examples
javastringbuildertextinput

Processing text files and hyphenating strings line by line in Java


I have a .txt file with 8,000 rows in a single column. Each line contains either an alphanumeric or a number like this:

0219381A

10101298

32192017

1720291C

04041009

I'd like to read this file, insert a 0 (zero) before each beginning digit, a hyphen in between digits 3 and 4, and then remove the remaining digits to an output file like this:

002-19

010-10

032-19

017-20

004-04

I'm able to read from and write to a file or insert a hyphen when done separately but can't get the pieces working together:

public static void main(String[] args) throws FileNotFoundException{
          // TODO Auto-generated method stub

          Scanner in = new Scanner(new File("file.txt"));
          PrintWriter out = new PrintWriter("file1.txt");

          while(in.hasNextLine())
          {

                 StringBuilder builder = new StringBuilder(in.nextLine());
                 builder.insert(0, "0");
                 builder.insert(3, "-");
                 String hyph = builder.toString();
                 out.printf(hyph);
          }
          in.close();
          out.close();

How can I get these pieces working together/is there another approach?


Solution

  • try this

        while (in.hasNextLine()) {
            String line = in.nextLine();
            if (!line.isEmpty()) {
                line = "0" + line.substring(0, 2) + "-" + line.substring(2, 4);
            }
            out.println(line);
        }