1

I want this programme to write numbers in my txt file but instead of that it writes some strange signs.Does anyone can fix it and make it write numbers from the array

package int1;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.channels.FileChannel;

public class broj_u_skl {
public static void main(String[] args) {
    File a = new File("C:\\Users\\Jovan\\Desktop");
    File b = new File(a,"Pisem.txt");
    try {
    b.createNewFile();
}catch(Exception e) {

}
    FileOutputStream st = null;
    try {
        st = new FileOutputStream(b);
    }catch(Exception e) {

    }

this is that array:

    int[] c = {1,2,3,4,5,6,7,8,9};

but it doesnt write this numbers above.

    ByteBuffer bff = ByteBuffer.allocate(100);
    FileChannel ch = st.getChannel();
    IntBuffer ib = bff.asIntBuffer();
    for (int i = 0; i < c.length; i++) {
        ib.put(c[i]);

    }
    bff.position(4*ib.position());
    bff.flip();
    try {
        ch.write(bff);
    }catch(IOException e) {

    }






   }
   }

4 Answers4

1

You can either close st in finally clause

FileOutputStream st = null;
try {
    st = new FileOutputStream(b);
    ...
} catch(Exception e) {
    ...
} finally {
    st.close();
}

or a better solution is to use a try-with-resources clause which will close st for you.

try (FileOutputStream st = new FileOutputStream(b)) {
   ...
} catch(Exception e) {
   ...
}
jeanr
  • 1,031
  • 8
  • 15
0

Add following code

finally{
 st.close();
 }
mohit sharma
  • 1,050
  • 10
  • 20
0

What this is doing is writing the integers as bytes to the file, not as ascii strings.

Have a look at the example at how to write an array to a file Java

davidsheldon
  • 38,365
  • 4
  • 27
  • 28
0

Your writing integers as bytes, but to have them correctly shown as ascii strings change your IntBuffer to an CharBuffer :

    CharBuffer charBuffer = byteBuffer.asCharBuffer();
        for (int i = 0; i < c.length; i++) {
            charBuffer.put("" + c[i]);
        }

and don't forget to flush and close your FileOutputStream:

    finally {
        outputStream.flush();
        outputStream.close();
    }
KilledByCheese
  • 852
  • 10
  • 30