java.io.RandomAccessFile फाइल में रैंडम एक्सेस (कहीं भी पढ़ें/लिखें) की अनुमति देता है। एक फाइल पॉइंटर स्थिति ट्रैक करता है।
लाइन-बाय-लाइन पढ़ने के लिए चरण
Fileऑब्जेक्ट बनाएंRandomAccessFileको मोड"r"(रीड-ओनली) या"rw"(रीड/राइट) के साथ खोलेंgetFilePointer() < length()के साथ लूप करेंreadLine()से प्रत्येक लाइन पढ़ेंStringBuilderमें जोड़ें- बंद करें
उदाहरण
import java.io.*;
public class RandomAccessFileRead {
public static void main(String args[]) throws IOException {
String filePath = "D://input.txt";
File file = new File(filePath);
StringBuilder buffer = new StringBuilder();
try (RandomAccessFile raf = new RandomAccessFile(file, "r")) {
while (raf.getFilePointer() < raf.length()) {
buffer.append(raf.readLine()).append(System.lineSeparator());
}
}
System.out.println("File contents:\n" + buffer.toString());
}
}आउटपुट
File contents: Tutorials Point originated from the idea that there exists a class of readers... Enjoy the free content
मुख्य विधियाँ
seek(long pos): पॉइंटर को स्थिति पर ले जाएंgetFilePointer(): वर्तमान स्थिति प्राप्त करेंlength(): फाइल लंबाईreadInt(),readUTF(), आदि: टाइप्ड रीड
उपयोग का मामला
बड़ी फ़ाइलों के विशिष्ट भागों को पढ़ने/लिखने के लिए उपयोगी बिना पूरी फ़ाइल लोड किए (उदाहरण: लॉग टेलिंग, बाइनरी फ़ाइल पैचिंग)।