Code example for RandomAccessFile

Methods: writeBytes, writeInt, writeShort

0
        try { 
        	if(file.exists()){
        		file.delete();
        	} 
            file.createNewFile();
            randomAccessWriter = new RandomAccessFile(file.getPath(),"rw");
            randomAccessWriter.writeBytes("RIFF");
            randomAccessWriter.writeInt(0); // Final file size not known yet, write 0
            randomAccessWriter.writeBytes("WAVE");
            randomAccessWriter.writeBytes("fmt ");
            randomAccessWriter.writeInt(Integer.reverseBytes(16)); // Sub-chunk size, 16 for PCM
            randomAccessWriter.writeShort(Short.reverseBytes((short) 1)); // AudioFormat, 1 for PCM
            randomAccessWriter.writeShort(Short.reverseBytes((short)2));// Number of channels, 1 for mono, 2 for stereo
            randomAccessWriter.writeInt(Integer.reverseBytes(44100)); // Sample rate
            randomAccessWriter.writeInt(Integer.reverseBytes(44100*16*2/8)); // Byte rate, SampleRate*NumberOfChannels*BitsPerSample/8
            randomAccessWriter.writeShort(Short.reverseBytes((short)(2*16/8))); // Block align, NumberOfChannels*BitsPerSample/8
            randomAccessWriter.writeShort(Short.reverseBytes((short)16)); // Bits per sample
            randomAccessWriter.writeBytes("data");
            randomAccessWriter.writeInt(0); // Data chunk size not known yet, write 0
        } catch (IOException e) {
            e.printStackTrace();
        } 
    }