import java.nio.*; import java.io.*; import java.util.Arrays; public class ByteBufferReadWriteTest { /* this method is only for debugging. * Comment out code, where method is called. */ public static void print_array(byte[] array) { int i=0; for(byte b: array) { System.out.format("%x", b); if(++i % 2 == 0) System.out.print(" "); } System.out.println(); } public static void main(String []args ) { File file = new File("file.bin"); write(file); read(file); } public static void write(File file) { int a = -159954; double b = 125.128953; char c = 'θ'; String str = "Πώς είσαι;"; ByteBuffer buffer = ByteBuffer.allocate(512); buffer.order(ByteOrder.BIG_ENDIAN); buffer.putInt(a); buffer.putDouble(b); buffer.putChar(c); buffer.put(str.getBytes(java.nio.charset.StandardCharsets.UTF_8)); int buffer_size = buffer.position(); try(FileOutputStream out = new FileOutputStream(file)) { byte []array = buffer.array(); array = Arrays.copyOf(array, buffer_size); out.write(array); // just for debugging purposes //print_array(array); } catch(IOException ex) { System.out.println("Cannot write to file: "+file.getName()); } } public static void read(File file) { int a; double b; double c; byte array[] = new byte[512]; int read_size; try(FileInputStream in = new FileInputStream(file)) { read_size = in.read(array); array = Arrays.copyOf(array, read_size); } catch(IOException ex) { System.out.println("Cannot read from file: "+file.getName()); } // just for debugging purposes //print_array(array); ByteBuffer buffer = ByteBuffer.wrap(array); buffer.order(ByteOrder.BIG_ENDIAN); System.out.println(buffer.getInt()); System.out.println(buffer.getDouble()); System.out.println("'"+buffer.getChar()+"'"); int str_size = buffer.remaining(); byte[] bytes = new byte[str_size]; buffer.get(bytes); System.out.println(new String(bytes, java.nio.charset.StandardCharsets.UTF_8)); } }