Create Read Only File Java

Create Read Only File Java

In below sample program we will create new read only file using File class setWritable(false) operations.

  • CreateReadOnlyFile.java:
package com.javahonk;

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

public class CreateReadOnlyFile {

	public static void main(String[] args) {

		try {

			File file = new File("C:\\JavaHonk\\FileReadFile.txt");
			if (file.exists()) {
				file.delete();
			}

			file.createNewFile();

			// Set read-only make writable false
			file.setWritable(false);
			System.out.println("Is file writable: " + file.canWrite());

		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}
  • Output:

Create Read Only File Java

  • For more information about File API please refer oracle documentation here

Leave a Reply

Your email address will not be published. Required fields are marked *