How can I write to a file with multiple lines in java?

0

I have a method that generates 10,000 numbers and I store them in an array.

I would like these data to be written in a file of 10 lines with 1000 numbers per line.

This is what I have tried:

try {
        File f = new File(System.getProperty("user.dir") + "/datos.txt");//crea el archivo txt
        BufferedWriter bw;
        if (f.exists()) {
            bw = new BufferedWriter(new FileWriter(f));//se encargara de escribir en el txt
            for (int i = 0; i < lista.getLongitud(); i++) {
                bw.write((Integer) lista.obtenerNodo(i) + ",");//escribe los datos en el txt
            }
        bw.close();
        }
    } catch (Exception ex) {//si falla mandara el error generado
        JOptionPane.showMessageDialog(this, "Error en IO"+ ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
    }
    
asked by Alex Reyes 16.10.2017 в 02:13
source

1 answer

1

Guiding me by your description in the comments:

  

numbers separated by a comma, when you reach the 1000 numbers make   a line break

     

to write 10 rows of 1000 data each

In the following code a list of ten thousand numbers is created, which will be recorded in the file in lines of 1000 numbers.

In each iteration a block is created which will be downloaded to the file. This block is the concatenation of 1000 numbers separated by a comma, created from a sublist of the original list.

Each time you complete 1000 numbers you start writing a new line using bw.writeLine()

public static void main(String[] args)   {
         // Test raw data
         List<String> numbers = new ArrayList<String>();
         for(int i =1; i<=10000; i++) {
             numbers.add(""+i);
         }

         // File creation
         File f = new File("data.txt");
         if(!f.exists()) {
             try {
                f.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
         }

         // File writing
         try( FileWriter fr = new FileWriter(f);
                 BufferedWriter bw = new BufferedWriter(fr)){

             List<String> block = new ArrayList<String>();
             for(int i =0; i<numbers.size(); i+=1000) {
                 // writes a block with 1000 elements and creates a new line
                 block = numbers.subList(i, i+1000);
                 bw.write(String.join(",", block));
                 bw.newLine();
              }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
answered by 16.10.2017 / 03:33
source