Hierarchy of Applet Class IN java

Random Access File IN java

TheJava.io.RandomAccessFileclass file behaves like a large array of bytes stored in the file system.Instances of this class support both reading and writing to a random access file.

Class constructors

S.N. / Constructor & Description
1 / RandomAccessFile(File file, String mode)
This creates a random access file stream to read from, and optionally to write to, the file specified by the File argument.
2 / RandomAccessFile(File file, String mode)
This creates a random access file stream to read from, and optionally to write to, a file with the specified name.

Class methods

S.N. / Method & Description
1 / void close()
This method Closes this random access file stream and releases any system resources associated with the stream.
2 / FileChannel getChannel()
This method returns the unique FileChannel object associated with this file.
3 / FileDescriptor getFD()
This method returns the opaque file descriptor object associated with this stream.
4 / long getFilePointer()
This method returns the current offset in this file.
5 / long length()
This method returns the length of this file.
6 / int read()
This method reads a byte of data from this file.
7 / int read(byte[] b)
This method reads up tob.lengthbytes of data from this file into an array of bytes.
8 / int read(byte[] b, int off, int len)
This method reads up tolenbytes of data from this file into an array of bytes.
9 / boolean readBoolean()
This method reads a boolean from this file.
10 / byte readByte()
This method reads a signed eight-bit value from this file.
11 / char readChar()
This method reads a character from this file.
12 / double readDouble()
This method reads a double from this file.
13 / float readFloat()
This method reads a float from this file.
14 / void readFully(byte[] b)
This method reads b.length bytes from this file into the byte array, starting at the current file pointer.
15 / void readFully(byte[] b, int off, int len)
This method reads exactly len bytes from this file into the byte array, starting at the current file pointer.
16 / int readInt()
This method reads a signed 32-bit integer from this file.
17 / String readLine()
This method reads the next line of text from this file.
18 / long readLong()
This method reads a signed 64-bit integer from this file.
19 / short readShort()
This method reads a signed 16-bit number from this file.
20 / int readUnsignedByte()
This method reads an unsigned eight-bit number from this file.
21 / int readUnsignedShort()
This method reads an unsigned 16-bit number from this file.
22 / String readUTF()
This method reads in a string from this file.
23 / void seek(long pos)
This method sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs.
24 / void setLength(long newLength)
This method sets the length of this file.
25 / int skipBytes(int n)
This method attempts to skip over n bytes of input discarding the skipped bytes.
26 / void write(byte[] b)
This method writes b.length bytes from the specified byte array to this file, starting at the current file pointer.
27 / void write(byte[] b, int off, int len)
This method writes len bytes from the specified byte array starting at offset off to this file.
28 / void write(int b)
This method writes the specified byte to this file..
29 / void writeBoolean(boolean v)
This method writes a boolean to the file as a one-byte value.
30 / void writeByte(int v)
This method writes a byte to the file as a one-byte value.
31 / void writeBytes(String s)
This method writes the string to the file as a sequence of bytes.
32 / void writeChar(int v)
This method writes a char to the file as a two-byte value, high byte first.
33 / void writeChars(String s)
This method writes a string to the file as a sequence of characters.
34 / void writeDouble(double v)
This method converts the double argument to a long using the doubleToLongBits method in class Double, and then writes that long value to the file as an eight-byte quantity, high byte first.
35 / void writeFloat(float v)
This method converts the float argument to an int using the floatToIntBits method in class Float, and then writes that int value to the file as a four-byte quantity, high byte first.
36 / void writeInt(int v)
This method writes an int to the file as four bytes, high byte first.
37 / void writeLong(long v)
This method writes a long to the file as eight bytes, high byte first.
38 / void writeShort(int v)
This method writes a short to the file as two bytes, high byte first.
39 / void writeUTF(String str)
This method writes a string to the file using modified UTF-8 encoding in a machine-independent manner.

Creating a RandomAccessFile

Before you can work with theRandomAccessFileclass you must instantiate it. Here is how that looks:

RandomAccessFile file = new RandomAccessFile("c:\\data\\file.txt", "rw");

Notice the second input parameter to the constructor:"rw". This is the mode you want to open file in. "rw" means read/write mode. Check the JavaDoc for more details about what modes you can open aRandomAccessFilein.

Moving Around a RandomAccessFile

To read or write at a specific location in aRandomAccessFileyou must first position the file pointer at the location to read or write. This is done using theseek()method. The current position of the file pointer can be obtained by calling thegetFilePointer()method.

Here is a simple example:

RandomAccessFile file = new RandomAccessFile("c:\\data\\file.txt", "rw");

file.seek(200);

long pointer = file.getFilePointer();

file.close();

Reading from a RandomAccessFile

Reading from aRandomAccessFileis done using one of its manyread()methods. Here is a simple example:

RandomAccessFile file = new RandomAccessFile("c:\\data\\file.txt", "rw");

int aByte = file.read();

file.close();

Theread()method reads the byte located a the position in the file currently pointed to by the file pointer in theRandomAccessFileinstance.

Here is a thing the JavaDoc forgets to mention: Theread()method increments the file pointer to point to the next byte in the file after the byte just read! This means that you can continue to callread()without having to manually move the file pointer.

Writing to a RandomAccessFile

Writing to aRandomAccessFilecan be done using one it its manywrite()methods. Here is a simple example:

RandomAccessFile file = new RandomAccessFile("c:\\data\\file.txt", "rw");

file.write("Hello World".getBytes());

file.close();

Just like with theread()method thewrite()method advances the file pointer after being called. That way you don't have to constantly move the file pointer to write data to a new location in the file.

RandomAccessFile Exception Handling

The proper exception handling of aRandomAccessFileis left out of this text for clarity. However, aRandomAccessFilemust be closed properly after use, just like with a stream or reader / writer. To lean more, see the textJava IO Exception Handling.

Example

ava RandomAccessFile provides facility to read and write data to a file. RandomAccessFile works with file as large array of bytes and a cursor using which we can move thefile pointerposition.

While creating the instance of RandomAccessFile, we need to provide the mode of the file, for example “r” if you only want to read the file and “rw” if you want to read and write to the file.

Using file pointer, we can read or write data from random access file at any position. To get the current file pointer, you can callgetFilePointer()method and to set the file pointer index, you can callseek(int i)method.

If we write data at any index where data is already present, it will override it.

Here is a simple java random access file example.

importjava.io.IOException;

importjava.io.RandomAccessFile;

publicclassRandomAccessFileExample {

publicstaticvoidmain(String[] args) {

try{

String filePath = "/Users/pankaj/source.txt";

System.out.println(newString(readCharsFromFile(filePath, 1, 5)));

writeData(filePath, "Data", 5);

} catch(IOException e) {

e.printStackTrace();

}

}

privatestaticvoidwriteData(String filePath, String data, intseek) throwsIOException {

RandomAccessFile file = newRandomAccessFile(filePath, "rw");

file.seek(seek);

file.write(data.getBytes());

file.close();

}

privatestaticbyte[] readCharsFromFile(String filePath, intseek, intchars) throwsIOException {

RandomAccessFile file = newRandomAccessFile(filePath, "r");

file.seek(seek);

byte[] bytes = newbyte[chars];

file.read(bytes);

file.close();

returnbytes;

}

}

FILE class

Java File class represents the files and directory pathnames in an abstract manner. This class is used for creation of files and directories, file searching, file deletion etc.

The File object represents the actual file/directory on the disk. There are following constructors to create a File object:

Following syntax creates a new File instance from a parent abstract pathname and a child pathname string.

File(File parent, String child);

Following syntax creates a new File instance by converting the given pathname string into an abstract pathname.

File(String pathname)

Following syntax creates a new File instance from a parent pathname string and a child pathname string.

File(String parent, String child)

Following syntax creates a new File instance by converting the given file: URI into an abstract pathname.

File(URI uri)

Once you haveFileobject in hand then there is a list of helper methods which can be used manipulate the files.

SN / Methods with Description
1 / public String getName()
Returns the name of the file or directory denoted by this abstract pathname.
2 / public String getParent()
Returns the pathname string of this abstract pathname's parent, or null if this pathname does not name a parent directory.
3 / public File getParentFile()
Returns the abstract pathname of this abstract pathname's parent, or null if this pathname does not name a parent directory.
4 / public String getPath()
Converts this abstract pathname into a pathname string.
5 / public boolean isAbsolute()
Tests whether this abstract pathname is absolute. Returns true if this abstract pathname is absolute, false otherwise
6 / public String getAbsolutePath()
Returns the absolute pathname string of this abstract pathname.
7 / public boolean canRead()
Tests whether the application can read the file denoted by this abstract pathname. Returns true if and only if the file specified by this abstract pathname exists and can be read by the application; false otherwise.
8 / public boolean canWrite()
Tests whether the application can modify to the file denoted by this abstract pathname. Returns true if and only if the file system actually contains a file denoted by this abstract pathname and the application is allowed to write to the file; false otherwise.
9 / public boolean exists()
Tests whether the file or directory denoted by this abstract pathname exists. Returns true if and only if the file or directory denoted by this abstract pathname exists; false otherwise
10 / public boolean isDirectory()
Tests whether the file denoted by this abstract pathname is a directory. Returns true if and only if the file denoted by this abstract pathname exists and is a directory; false otherwise.
11 / public boolean isFile()
Tests whether the file denoted by this abstract pathname is a normal file. A file is normal if it is not a directory and, in addition, satisfies other system-dependent criteria. Any non-directory file created by a Java application is guaranteed to be a normal file. Returns true if and only if the file denoted by this abstract pathname exists and is a normal file; false otherwise.
12 / public long lastModified()
Returns the time that the file denoted by this abstract pathname was last modified. Returns a long value representing the time the file was last modified, measured in milliseconds since the epoch (00:00:00 GMT, January 1, 1970), or 0L if the file does not exist or if an I/O error occurs.
13 / public long length()
Returns the length of the file denoted by this abstract pathname. The return value is unspecified if this pathname denotes a directory.
14 / public boolean createNewFile() throws IOException
Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. Returns true if the named file does not exist and was successfully created; false if the named file already exists.
15 / public boolean delete()
Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, then the directory must be empty in order to be deleted. Returns true if and only if the file or directory is successfully deleted; false otherwise.
16 / public void deleteOnExit()
Requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates.
17 / public String[] list()
Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname.
18 / public String[] list(FilenameFilter filter)
Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.
20 / public File[] listFiles()
Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.
21 / public File[] listFiles(FileFilter filter)
Returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.
22 / public boolean mkdir()
Creates the directory named by this abstract pathname. Returns true if and only if the directory was created; false otherwise.
23 / public boolean mkdirs()
Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Returns true if and only if the directory was created, along with all necessary parent directories; false otherwise.
24 / public boolean renameTo(File dest)
Renames the file denoted by this abstract pathname. Returns true if and only if the renaming succeeded; false otherwise.
25 / public boolean setLastModified(long time)
Sets the last-modified time of the file or directory named by this abstract pathname. Returns true if and only if the operation succeeded; false otherwise.
26 / public boolean setReadOnly()
Marks the file or directory named by this abstract pathname so that only read operations are allowed. Returns true if and only if the operation succeeded; false otherwise.
27 / public static File createTempFile(String prefix, String suffix, File directory) throws IOException
Creates a new empty file in the specified directory, using the given prefix and suffix strings to generate its name. Returns an abstract pathname denoting a newly-created empty file.
28 / public static File createTempFile(String prefix, String suffix) throws IOException
Creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name. Invoking this method is equivalent to invoking createTempFile(prefix, suffix, null). Returns abstract pathname denoting a newly-created empty file.
29 / public int compareTo(File pathname)
Compares two abstract pathnames lexicographically. Returns zero if the argument is equal to this abstract pathname, a value less than zero if this abstract pathname is lexicographically less than the argument, or a value greater than zero if this abstract pathname is lexicographically greater than the argument.
30 / public int compareTo(Object o)
Compares this abstract pathname to another object. Returns zero if the argument is equal to this abstract pathname, a value less than zero if this abstract pathname is lexicographically less than the argument, or a value greater than zero if this abstract pathname is lexicographically greater than the argument.
31 / public boolean equals(Object obj)
Tests this abstract pathname for equality with the given object. Returns true if and only if the argument is not null and is an abstract pathname that denotes the same file or directory as this abstract pathname.
32 / public String toString()
Returns the pathname string of this abstract pathname. This is just the string returned by the getPath() method.

Following is the example to demonstrate File object:

package com.tutorialspoint;

import java.io.File;

public class FileDemo {

public static void main(String[] args) {

File f = null;

String[] strs = {"test1.txt", "test2.txt"};

try{

// for each string in string array

for(String s:strs )

{

// create new file

f= new File(s);

// true if the file is executable

boolean bool = f.canExecute();

// find the absolute path

String a = f.getAbsolutePath();

// prints absolute path

System.out.print(a);

// prints

System.out.println(" is executable: "+ bool);

}

}catch(Exception e){

// if any I/O error occurs

e.printStackTrace();

}

}

}

Consider there is an executable file test1.txt and another file test2.txt is non executable in current directory, Let us compile and run the above program, this will produce the following result:

test1.txt is executable: true

test2.txt is executable: false

Examples and Sample Code of File Class

TheFileclass in the Java IO API gives you access to the underlying file system. Using theFileclass you can:

Check if a file exists.

Read the length of a file.

Rename or move a file.

Delete a file.

Check if path is file or directory.

Read list of files in a directory.

This text will tell you more about how.

Note: TheFileonly gives you access to the file and file system meta data. If you need to read or write the content of files, you should do so using eitherFileInputStream,FileOutputStreamorRandomAccessFile.

Note: If you are using Java NIO you will have to use thejava.nio.FileChannelclass instead (you can use both, but in case you want a pure Java NIO solution).

Instantiating a java.io.File