Files

RandomAccessFile
public RandomAccessFile(File file,String mode)

throws FileNotFoundExceptionCreates a random access file stream to read from, and optionally to write to, the file specified by the File argument. A new FileDescriptor object is created to represent this file connection.

The mode argument specifies the access mode in which the file is to be opened. The permitted values and their meanings are:

"r" - Open for reading only. Invoking any of the write methods of the resulting object will cause an IOException to be thrown.
"rw" - Open for reading and writing. If the file does not already exist then an attempt will be made to create it.
"rws" -Open for reading and writing, as with "rw", and also require that every update to the file's content or metadata be written synchronously to the underlying storage device.
"rwd" -Open for reading and writing, as with "rw", and also require that every update to the file's content be written synchronously to the underlying storage device.

  • In the code below
File f = new File("hello.test");
FileOutputStream out = new FileOutputStream(f);

The first line creates a File object that represents the file. By creating a FileOutputStream, you create the file if it does not yet exist, and open that file for reading and writing.

  • Q - How can you replace the comment at the end of main() with code that will write the integers 0 through 9?
import java.io.*;

class Write {
public static void main(String[] args) throws Exception {
File file = new File("temp.test");
FileOutputStream stream = new FileOutputStream(file);
// write integers here. . .
}
}

A - In order to write a primitive data type such as an int, you need to use a FilterOutputStream subclass such as DataOutputStream. This class defines writeInt.


DataOutputStream filter = new DataOutputStream(stream);
for (int i = 0; i < 10; i++)
filter.writeInt(i);

  • This code compiles and runs fine. RandomAccessFile implements the DataOutput interface, so it does implement writeBytes(), among others. RandomAccessFile creates the file if it does not yet exist.
import java.io.*;

class Ran {

public static void main(String[] args) throws IOException {
RandomAccessFile out = new RandomAccessFile("Ran.test", "rw");
out.writeBytes("Ninotchka");
}
}

Comments

Popular posts from this blog

jQgrid reload with new data

Rich Client based UI technologies- A Comparison of Thick Client UI tools

OSS and BSS Systems