সাধারণ ফাইল I/O-তে শুধু সিকোয়েনশিয়ালি (শুরু থেকে শেষে) পড়া/লিখা যায়। java.io.RandomAccessFile ক্লাস ব্যবহার করে ফাইলের যেকোনো র্যান্ডম পজিশন থেকে পড়া/লিখা যায়। এটি একটি বড় বাইট অ্যারের মতো কাজ করে যেখানে একটি ফাইল পয়েন্টার (Cursor) থাকে।
মূল মেথডসমূহ
getFilePointer(): বর্তমান পয়েন্টার পজিশন রিটার্ন করে।seek(long pos): পয়েন্টার নির্দিষ্ট পজিশনে সরিয়ে দেয়।readLine(): পরবর্তী লাইন পড়ে স্ট্রিং রিটার্ন করে।length(): ফাইলের দৈর্ঘ্য (বাইটে)।
উদাহরণ: RandomAccessFile দিয়ে ফাইল পড়া
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFileExample {
public static void main(String args[]) throws IOException {
String filePath = "D://input.txt";
// ১. File অবজেক্ট
File file = new File(filePath);
// ২. StringBuffer কন্টেন্ট জমা করার জন্য
StringBuffer buffer = new StringBuffer();
// ৩. RandomAccessFile ইনস্ট্যানশিয়েট (rw = read/write)
RandomAccessFile raFile = new RandomAccessFile(file, "rw");
// ৪. ফাইল পড়া (পয়েন্টার < দৈর্ঘ্য পর্যন্ত)
while(raFile.getFilePointer() < raFile.length()) {
buffer.append(raFile.readLine() + System.lineSeparator());
}
String contents = buffer.toString();
System.out.println("Contents of the file: \n" + contents);
}
}
আউটপুট
Contents of the file: Tutorials Point originated from the idea that there exists a class of readers who respond better to online content and prefer to learn new skills. Our content and resources are freely available and we prefer to keep it that way to encourage our readers acquire as many skills as they would like to. We don't force our readers to sign up with us or submit their details either. Enjoy the free content
ব্যবহার ক্ষেত্র: বড় ফাইলের নির্দিষ্ট অংশ পড়া/লিখা, ফাইল সিকিং (seeking), র্যান্ডম অ্যাক্সেস ডাটাবেস ইমপ্লিমেন্টেশন। সাধারণ টেক্সট ফাইল পড়ার জন্য BufferedReader বা Scanner সহজ ও দক্ষ।