Cách tạo một file chỉ dùng để đọc

Một chương trình Java để chứng minh việc sử dụng phương thức setReadOnly() java.io.File để tạo một file chỉ đọc. Kể từ JDK 1.6, phương thức setWritable(), sử dụng để có thể ghi được file.

Table of Contents

Thí dụ

package com.itphutran.file;

import java.io.File;
import java.io.IOException;

public class FileReadAttribute {

	public static void main(String[] args) throws IOException {
		File file = new File("E:\\project\\huongdanjava\\javaio\\testdemo.txt");

		// mark this file as read only, since jdk 1.2
		file.setReadOnly();

		if (file.canWrite()) {
			System.out.println("This file is writable");
		} else {
			System.out.println("This file is read only");
		}

		// revert the operation, mark this file as writable, since jdk 1.6
		file.setWritable(true);

		if (file.canWrite()) {
			System.out.println("This file is writable");
		} else {
			System.out.println("This file is read only");
		}
	}
}

Đầu ra

This file is read only
This file is writable

 

Để lại một bình luận

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *

x