Search code examples
javafilecopy

java - copy specific rows from a file to another file


I have a file with the following format:

.ID 1
.Customers
A customer
One girl
.Products
Milk
Oil
Silk
.Date
12-1-2000
.ID2
.Customers
Anna Tall
.Products
Hairspray
.Date
21-5-2001
.ID 3
.Customers
Jane Eldest
Tom Ford
.Products
Shampoo

etc.

I would like to make different files, named for exaple 1.txt, 2.txt, 3.txt etc, in which files I want to have the following lines: .Customers(lines of customers) .Date(line of date), or if .Date does not exist, only .Customers. Each line starting with .ID determines a different new file. How could I do that? Thank you all in advance :)


Solution

  • Just an skeleton so you can continue yourself:

    public class Test {
    
        public static void main(String[] args) throws IOException {
            BufferedReader reader = new BufferedReader(new FileReader("file"));
            String line;
            State state = null;
            while ((line = reader.readLine()) != null) {
                if (line.startsWith(".")) {
                    // detect state
                } else {
                    // handle data for state
                }
            }
        }
    
        static enum State {
            CUSTOMER, PRODUCTS, STATE;
        }
    }