How to Read in a Random File Java
Random access file is a special kind of file in Java that allows non-sequential or random admission to any location in the file. This means you don't demand to showtime from 1st line if you want to read line number 10, yous can directly become to line 10 and read. Information technology's similar to the array information structure, Simply like you lot can access any chemical element in the assortment by alphabetize you can read any content from the file past using a file pointer. A random-access file actually behaves like a large array of bytes stored in the file system and that's why information technology's very useful for low latency applications which need some kind of persistence e.k. in front end role trading application and Set Engine, you tin use random access file to shop FIX sequence numbers or all open orders.
This will be handy when you recover from the crash and you need to build your in-retention enshroud to the land just before the crash. RandomAccessFile provides you the ability to read and write into whatever random access file. When you lot read content from a file, y'all start with the current location of the file arrow, and the arrow is moved forrad past how many bytes are read.
Similarly, when you write information into the random access file, it starts writing from the current location of the file pointer and so advances the file pointer past the number of files written. Random access is achieved by setting a file pointer to whatever arbitrary location using theseek() method.
You can also get the current location by calling thegetFilePointer() method. In that location are ii master ways to read and write information into RandomAccessFile, either you can use Channel similarSeekableByteChannel and ByteBuffer class from Java NIO, this allows you to read information from file to byte buffer or write data from byte buffer to random admission file.
Alternatively you lot tin can besides use various read() and write() method from RandomAccessFile likereadBoolean(), readInt(), readLine() or readUTF(). This is a 2-part Java IO tutorial, in this part, we will learn how to read and write String from RandomAccess file in Java without using Java NIO channels, and in the next part, nosotros will larn how to read bytes using ByteBuffer and Channel API.
And, If you are new to the Java world then I as well recommend you go throughThe Complete Java MasterClasson Udemy to acquire Coffee in a better and more structured fashion. This is ane of the best and upwardly-to-date courses to learn Java online.
How to Read/Write into Random Access File
In order to write data into random access file, you get-go need to create an instance of RandomAccessFile form in reading and write mode. You can do this by passing "rw" as the mode to the constructor. One time y'all accept washed that y'all can either use SeekableByteChannel or seek() method to fix the pointer to a location where y'all desire to write data.
You tin either write bytes using ByteBuffer and Java NIO Channel API or you can write int, float, string, or any other Java data type by using corresponding writeInt(), writeFloat(), and writeUTF() methods.
All these methods are defined in coffee.io.RandomAccessFile class in the Java IO package. When y'all write data that exceeds the current size of the file caused random access file to be extended. For reading data from random access, you can either open up the file into theread-but mode or read write mode.
Just like writing, you lot tin can also perform reading either by using Aqueduct API and ByteBuffer class ( you should if you are using Java NIO ) or traditional methods defined in RandomAccessFile in Coffee. Only like you lot accept different write methods to write different data types yous too take corresponding read methods to read them dorsum.
In society to read from a random location, y'all can use seek() method to set the file pointer to a particular location in the file. Past the way, if the stop of the file is reached before your program reads the desired number of bytes, an EOFException will be thrown. If whatsoever byte cannot be read due to whatsoever other reason then IOException will be thrown.
RandomAccessFile Example in Java
Following is our sample Java program to demonstrate how you can read or write String from a RandomAccessFile. The file name is "sample.store" which will be created in the current directory, usually in your projection directory if yous are using Eclipse IDE.
We have two utility methods to read String from random access file and write a string into a file, both methods take an int location to demonstrate random read and random write operation. In club to write and read String, we will exist using thewriteUTF() and readUTF() method, which reads String in modified UTF-8 format.
Though in this program, I have closed file in the try block, you should e'er do that in a finally block with an additional try block, or better utilize try-with-resource statement from Coffee 7. I will bear witness y'all how you can practise that in the side by side part of this tutorial when we will larn to read and writing byte arrays using ByteBuffer and SeekableByteChannel course.
import coffee.io.FileNotFoundException; import coffee.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; /** * Java Program to read and write UTF String on RandomAccessFile in Coffee. * * @author Javin Paul */ public class RandomAccessFileDemo{ public static void main(Cord args[]) { String data = "KitKat (four.4 - 4.4.2)"; writeToRandomAccessFile("sample.store", 100, data); System .out.println("String written into RandomAccessFile from Coffee Plan : " + data); Cord fromFile = readFromRandomAccessFile("sample.store", 100); System .out.println("String read from RandomAccessFile in Coffee : " + fromFile); } /* * Utility method to read from RandomAccessFile in Coffee */ public static String readFromRandomAccessFile(String file, int position) { Cord tape = cipher; effort { RandomAccessFile fileStore = new RandomAccessFile(file, "rw"); // moves file arrow to position specified fileStore.seek(position); // reading String from RandomAccessFile record = fileStore.readUTF(); fileStore.shut(); } grab (IOException e) { e.printStackTrace(); } return record; } /* * Utility method for writing into RandomAccessFile in Java */ public static void writeToRandomAccessFile(String file, int position, Cord record) { attempt { RandomAccessFile fileStore = new RandomAccessFile(file, "rw"); // moves file pointer to position specified fileStore.seek(position); // writing Cord to RandomAccessFile fileStore.writeUTF(record); fileStore.close(); } catch (IOException east) { e.printStackTrace(); } } } Output : String written into RandomAccessFile from Coffee Program : KitKat (4.four - 4.iv.two) String read from RandomAccessFile in Coffee : KitKat (4.4 - 4.four.2)
That's all nearly how to read and write from RandomAccessFile in Java. Y'all would be surprised that this class is available from JDK ane.0 itself. It is indeed a very useful class from traditional Java IO API, which was the merely source of doing high-speed IO before Coffee NIO came with the memory-mapped file.
If y'all like this Java IO tutorial and are hungry for more than checkout following tutorials :
- How to read/write XML files in Java using DOM Parser? (program)
- How to read a text file in Coffee? (solution)
- How to check if a file is hidden in Coffee? (tutorial)
- How to make a JAR file in Java? (steps)
- How to read Properties file in Coffee? (program)
- How to create File and Directory in Java? (solution)
- How to read file line by line using BufferedReader in Java? (solution)
- How to write JSON Cord to file in Java? (solution)
- How to change File permissions in Java? (program)
- How to append text to a file in Java? (example)
- How to parse XML step by step using SAX Parser? (solution)
- How to copy Files in Java? (program)
- How to Upload File in Coffee web awarding using Servlets? (demo)
- Difference between getPath(), getAbsolutePath() and getRelativePath()? (difference)
Thank you for reading this Java RandomAccess tutorial so far. If you like this Java NIO tutorial and case so please share information technology with your friends and colleagues. If you have any questions or feedback, please driblet a note.
Source: https://javarevisited.blogspot.com/2015/02/randomaccessfile-example-in-java-read-write-String.html
0 Response to "How to Read in a Random File Java"
Post a Comment