Writing arraysList in txt java files

2

I am trying to write an arrayList in a text file with this function:

    String ruta = "C:\Users\usuario\Desktop\archivo1.txt";
    File f = new File(ruta);
    FileWriter fw = new FileWriter(f);
    BufferedWriter escritura = new BufferedWriter(fw);
    for(int i=0;i<lista.size();i++){
        escritura.write(lista.get(i));
        escritura.newLine();

    }
    escritura.close();
}

It's a Arralist integer that contains the values 0,1,2,3,4 and what appears to me is this

What can be the fault? Can not be done with bufferedWriter?.

Thank you very much.

    
asked by Borja Sanchez 16.02.2017 в 12:04
source

3 answers

3

For what I see you need to convert the value you get by Lista.get(i) to string , since it is not treating it as such since if we see that these ASCII symbols are in hexadecimal value we have to:

NUL 00--SOH 01--STX 02--ETX 03--EOT 04--ENQ 05

Edit: I add the code to parse the int to string of either of them will be worth

Integer.toString(Lista.get(i)) o String.valueOf(Lista.get(i))
    
answered by 16.02.2017 в 12:19
0

Try passing each Integer to String first:

String ruta = "C:\Users\usuario\Desktop\archivo1.txt";
    File f = new File(ruta);
    FileWriter fw = new FileWriter(f);
    BufferedWriter escritura = new BufferedWriter(fw);
    for(int i=0;i<Lista.size();i++){
        escritura.write(Integer.toString(Lista.get(i)));
        escritura.newLine();

    }
    escritura.close();
    
answered by 16.02.2017 в 12:15
0

The problem is that the class BufferedWriter is writing the numbers as binary bytes instead of as ASCII characters.

If you change the class of the writing object to an object of type Printwriter this will internally cast the numbers to characters automatically.

    String ruta = "C:\Users\usuario\Desktop\archivo1.txt";
    File f = new File(ruta);
    FileWriter fw = new FileWriter(f);
    PrintWriter escritura = new PrintWriter(fw);
    for(int i=0;i<lista.size();i++){
         escritura.println(lista.get(i));
    }
    escritura.close();
}
    
answered by 16.02.2017 в 16:30