Code example for RandomAccessFile

Methods: setLength, writeBytes, writeInt, writeShort

0
					if ((audioRecorder.getState() == AudioRecord.STATE_INITIALIZED)
							& (filePath != null)) {
						// write file header 
 
						randomAccessWriter = new RandomAccessFile(filePath,
								"rw"); 
 
						randomAccessWriter.setLength(0); // Set file length to
															// 0, to prevent 
															// unexpected 
															// behavior in case 
															// the file already 
															// existed 
						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(nChannels));// Number of channels,
															// 1 for mono, 2 for 
															// stereo 
						randomAccessWriter
								.writeInt(Integer.reverseBytes(sRate)); // Sample
																		// rate 
						randomAccessWriter.writeInt(Integer.reverseBytes(sRate
								* bSamples * nChannels / 8)); // Byte rate,
																// SampleRate*NumberOfChannels*BitsPerSample/8 
						randomAccessWriter
								.writeShort(Short
										.reverseBytes((short) (nChannels
												* bSamples / 8))); // Block
																	// align, 
																	// NumberOfChannels*BitsPerSample/8 
						randomAccessWriter.writeShort(Short
								.reverseBytes(bSamples)); // Bits per sample
						randomAccessWriter.writeBytes("data");
						randomAccessWriter.writeInt(0); // Data chunk size not
														// known yet, write 0 
 
						buffer = new byte[framePeriod * bSamples / 8
								* nChannels];
						state = State.READY;