Click here to watch in Youtube :
Click the below Image to Enlarge
Java Tutorial : Java IO (Java RandomAccessFile - V3) |
Java Tutorial : Java IO (Java RandomAccessFile - V3) |
John visits to india.
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFileReadDemo
{
public static void main(String[] args) throws IOException
{
RandomAccessFileReadDemo randomAccessFileReadDemo = new RandomAccessFileReadDemo();
byte[] byteArray = randomAccessFileReadDemo.readFromFile("myfile.txt",15);
System.out.println(new String(byteArray));
}
private byte[] readFromFile(String fileName, int position)
throws FileNotFoundException, IOException
{
RandomAccessFile randomAccessFile = null;
byte[] byteArray;
try
{
randomAccessFile = new RandomAccessFile(fileName, "r");
/*
* Sets the file-pointer offset, measured from
* the beginning of this file, at which the next
* read or write occurs.
*/
randomAccessFile.seek(position);
byteArray = new byte[5];
randomAccessFile.read(byteArray);
}
finally
{
if (randomAccessFile != null)
{
randomAccessFile.close();
}
}
return byteArray;
}
}
india
RandomAccessFileWriteDemo.javaimport java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFileWriteDemo
{
public static void main(String[] args) throws IOException
{
RandomAccessFileWriteDemo randomAccessFileWriteDemo = new RandomAccessFileWriteDemo();
randomAccessFileWriteDemo.writeToFile("myfile.txt", " and USA", 20);
}
private void writeToFile(String fileName, String data, int position)
throws IOException
{
RandomAccessFile randomAccessFile = null;
try
{
randomAccessFile = new RandomAccessFile(fileName, "rw");
/*
* Sets the file-pointer offset, measured from
* the beginning of this file, at which the next
* read or write occurs.
*/
randomAccessFile.seek(position);
randomAccessFile.write(data.getBytes());
System.out.println("Successfully written to the file.");
}
finally
{
if (randomAccessFile != null)
{
randomAccessFile.close();
}
}
}
}
Successfully written to the file.
Click the below link to download the code:
No comments:
Post a Comment