Cách sử dụng RandomAccessFile (java.io package) trong java

Trong bài viết này tôi sẽ hướng dẫn các bạn cách để sử dụng lớp RandomAccessFile, lớp RandomAccessFile nằm trong gói java.io.Nó có thể cấp quyền cho các bạn đọc hoặc ghi file, cũng có thể truy cập ngẫu nhiên, đưa con trỏ đến vị trí mong muốn.

Lớp RandomAccessFile gồm có 2 constructor tương ứng bên dưới:

Constructor lớp RandomAccessFile

RandomAccessFile(File file, String mode)
RandomAccessFile(String file, String mode)

Trong đó:

RandomAccessFile(File file, String mode)

File: là đối tượng file trỏ đến file hiện tại đang muốn đọc, viết

mode: là quyền truy cập hay nói cách khác là chế độ.

RandomAccessFile(String file, String mode)

Trong đó:

String file: là đường dẫn file

mode: là quyền truy cập hay nói cách khác là chế độ.

Với mode ta có các chế độ như sau:

 

Chế độ ý nghĩa
r Chỉ dùng để đọc và không thể viết
rw Dùng để đọc và viết

Ngoài ra còn hai chế độ rws và rwd nhưng ít sử dụng nên tôi không viết trong bài này.

Ví dụ và hướng dẫn sử dụng lớp

RandomAccessFile và các phương thức hay sử dụng:

Tôi sẽ đọc tất cả nội dung có trong file demo.txt như sau:

public static void main(String[] args) throws IOException {
		String filePath = "test\\demo.txt";
		 RandomAccessFile randomFile = null;
		try {
		 
		    randomFile = new RandomAccessFile(new File(filePath), "rw");
		    int r = 0;
		    while ((r  = randomFile.read()) != - 1) {
				System.out.print((char)r);
			}
		   
		} catch (IOException ex) {
		    System.err.println("I/O Error Exception: " + ex);
		} finally {
			if( randomFile != null) {
				 randomFile.close();
			}
		}
	}

Trường hợp này tôi đang ở chế độ cho phép vừa đọc và vừa viết file.

Kết quả như sau:

Chieu nay khong co mua bay

Dưới là nội dùng file demo.txt

setLength(int length) : tùy chỉnh độ dài bắt đầu từ 0: trả về độ dài mới của file

public static void main(String[] args) throws IOException {
		String filePath = "test\\demo.txt";
		RandomAccessFile randomFile = null;
		try {
		 
		    randomFile = new RandomAccessFile(new File(filePath), "rw");
		    int r = 0;
		    while ((r  = randomFile.read()) != - 1) {
				System.out.print((char)r);
			}
		    
		    randomFile.setLength(5);
		   
		    while ((r  = randomFile.read()) != - 1) {
				System.out.print((char)r);
			}
		   
		} catch (IOException ex) {
		    System.err.println("I/O Error Exception: " + ex);
		} finally {
			if( randomFile != null) {
				 randomFile.close();
			}
		}
	}

Ở đoạn code trên, ta set độ dài mới  là 5. Vì vậy kết quả output sẽ là:

Chieu

seek(long pos) : đưa con trỏ đến vị trí mong muốn trong file

public static void main(String[] args) throws IOException {
		String filePath = "test\\demo.txt";
		RandomAccessFile randomFile = null;
		try {
		 
		    randomFile = new RandomAccessFile(new File(filePath), "rw");
		    int r = 0;
		    while ((r  = randomFile.read()) != - 1) {
				System.out.print((char)r);
			}
		    
		    randomFile.setLength(5);
		   
		    while ((r  = randomFile.read()) != - 1) {
				System.out.print((char)r);
			}
		    
		    randomFile.seek(randomFile.length() + 1);
		    String str = "Lang tham mot tinh yeu....";
		    randomFile.write(str.getBytes());
		   
		} catch (IOException ex) {
		    System.err.println("I/O Error Exception: " + ex);
		} finally {
			if( randomFile != null) {
				 randomFile.close();
			}
		}
	}

Đoạn code trên sẽ có kết quả như sau:

Từ đó, ta thấy đầu tiên kết quả lúc đầu là Chieu, sau đó tôi sử dụng:

randomFile.seek(randomFile.length() + 1);

Hàm seek để di chuyển đến vị trí cần chèn, lúc này tôi muốn đến sau chuỗi hiện tai trong file và cách ra một space, lúc này ta có:

randomFile.length() : Đếm độ dài file hiện tại

Sau đó dùng hàm randomFile.write để viết file.

Trên là hướng dẫn sử dụng lớp RandomAccessFile , chúc các bạn học tốt!

0 0 đánh giá
Đánh giá bài viết
Theo dõi
Thông báo của
guest
0 Góp ý
Phản hồi nội tuyến
Xem tất cả bình luận
x