How to copy a text file odd lines and another file even lines and dump it in another

0

and so with all the lines one by one line so that it is

archivo1linea1 (nueva linea)
archivo2linea1 (nueva linea)
archivo1linea2 (nueva linea)
archivo2linea2 (nueva linea)

Code

public static void main(String[] args) throws IOException {
      String line = "";
    try (BufferedReader br = new BufferedReader(new FileReader("origen.txt"))) {

        try (BufferedReader br1 = new BufferedReader(new FileReader("origen1.txt"))) {

            try (BufferedWriter bw = new BufferedWriter(new FileWriter("destino.txt", true));) {

                while ((line = br.readLine()) != null)  {
                    bw.write(line);
                    bw.newLine();
                    br.readLine();
                   line=br1.readLine();
                   bw.write(line);
                   bw.newLine();
                   br1.readLine();


                }


            }
        }
    }
    
asked by user7407723 10.10.2017 в 03:29
source

1 answer

2

To work more easily with even and odd lines, I propose you to dump the contents of the files to each ArrayList<String> and work with them.

Dump the content of BufferedWriter to ArrayList<String>

This can be done in several ways. From Java-8 , it's almost trivial:

// Java 8
try (BufferedReader brPar = new BufferedReader(new FileReader("origen.txt"))) {
    List<String> pares = brPar.lines().collect(Collectors.toList());
}

With Java-7 , it's a bit more complicated:

// Java 7
try (BufferedReader brImpar = new BufferedReader(new FileReader("origen2.txt")))
{
    String line;
    impares = new ArrayList<>();
    while ((line = brImpar.readLine()) != null) {
        impares.add(line);
    }
}

Maybe you can separate it in another method like this:

private List<String> volcarALista(BufferedReader reader) throws IOException
{
    String line;
    List<String> lista = new ArrayList<>();
    while ((line = reader.readLine()) != null) {
        lista.add(line);
    }
    return lista;
}

// Java 7
try (BufferedReader brImpar = new BufferedReader(new FileReader("origen2.txt")))
{
    impares = volcarALista(brImpar);
}

Work with your ArrayList<String>

When you have filled them, working with your lists requires a simple % for :

try (BufferedWriter bw = new BufferedWriter(new FileWriter("destino.txt"))) {
    for (int i = 0; i < pares.size(); i++) {
        bw.write(impares.get(i));
        bw.newLine();
        bw.write(pares.get(i));
        bw.newLine();
    }
}

Although you think if your files do not have the same number of lines, this could lead to errors . You could solve it by checking which list is bigger.

    
answered by 11.10.2017 / 10:45
source