- How to make a file read only in Java
- You might also like.
- How To Make A File Read Only Or Writable In Java?
- 1. Overview
- 2. Java Example To Set File As Read Only
- 3. Java Example To Check File Can Be Writable
- 4. Java Example To Make Writable from Read Only Form
- 5. Conclusion
- Labels:
- SHARE:
- About Us
- Java 8 Tutorial
- Java Threads Tutorial
- Kotlin Conversions
- Kotlin Programs
- Java Conversions
- Java String API
- Spring Boot
- $show=Java%20Programs
- $show=Kotlin
- Making a File Read-Only in Java
- How to make a File Read Only in Java
- 1) Changing file attributes to read only
- 2) Check whether the file is writable or read only
- 3) How to make a read only file writable in java
How to make a file read only in Java
In this article, you’ll learn how to make a file read-only using Java. To make a file read-only in Java, you can use the File.setReadOnly() method. Here is an example:
File file = new File("input.txt"); // make file read-only file.setReadOnly(); // verify if the file is made read-only if (!file.canWrite()) System.out.println("File is read-only."); > else System.out.println("File is writable."); >
Alternatively, you can use the File.setWritable() method (Java 6+) to mark any file read-only as shown below:
File file = new File("input.txt"); // make file read-only file.setWritable(false); // verify if the file is made read-only if (!file.canWrite()) System.out.println("File is read-only."); > else System.out.println("File is writable."); >
To make any read-only file writable, you can use the same File.canWrite() method:
File file = new File("input.txt"); // make the file writable file.setWritable(true);
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.
You might also like.
How To Make A File Read Only Or Writable In Java?
A quick guide on how to make a file read only in java using setReadOnly() method from File API.
1. Overview
In this article, We’ll learn how to make a file as read only in java. After creating the file in java, we have to specify the file property readOnly flag to true. But, we can not set this flag to true directly.
File api has a utility method setReadOnly() method which returns a boolean value. True is returned if the file is successfully changed to read only form else false is returned.
2. Java Example To Set File As Read Only
Now let us create a class which creates a new File with name make-read-only.txt file. After that just call the method setReadOnly() method. That’s all now this file is set to only read only operations.
package com.javaprogramto.files.readonlywrite; import java.io.File; /** * Example to set the file as read-only format. * * @author javaprogramto.com * */ public class FileReadOnlyExample < public static void main(String[] args) < File newFile = new File("src/main/java/com/javaprogramto/files/readonlywrite/make-read-only.txt"); // setting the file as read only boolean isSetToReadOnly = newFile.setReadOnly(); System.out.println("isSetToReadOnly value : "+isSetToReadOnly); if(isSetToReadOnly) < System.out.println("make-read-only.txt is set to read-only form"); >else < System.out.println("Failed to set file as read only for make-read-only.txt"); >> >
isSetToReadOnly value : true make-read-only.txt is set to read-only form
3. Java Example To Check File Can Be Writable
In the above section, we have made the file as read only, but let us check now wether the file is allowed for the modifications or not.
Java File API has another method canWrite() which returns true if the file writable else false that means file is read only.
Look at the below example program. We are just passing the same file name to the File class and directly checking with canWrite() method.
package com.javaprogramto.files.readonlywrite; import java.io.File; /** * Example to check the file is writable or not. * * @author javaprogramto.com * */ public class FileCanWriteExample < public static void main(String[] args) < File newFile = new File("src/main/java/com/javaprogramto/files/readonlywrite/make-read-only.txt"); // checking the is allowed for modifications. boolean isSetToReadOnly = newFile.canWrite(); System.out.println("Can write the file ? : " + isSetToReadOnly); File breandNewFile = new File("src/main/java/com/javaprogramto/files/readonlywrite/make-new-file.txt"); // checking the is allowed for modifications. isSetToReadOnly = breandNewFile.canWrite(); System.out.println("Can write the breandNewFile file ? : " + isSetToReadOnly); >>
Can write the file ? : false Can write the breandNewFile file ? : true
4. Java Example To Make Writable from Read Only Form
Next, let us use the same read-only file and try to change its property to writable using setWritable(boolean).
This method is very useful when you are working with the unix platform and we can change the files permissions easily from programming.
package com.javaprogramto.files.readonlywrite; import java.io.File; /** * Example to convert the file from read only to writable form. * * @author javaprogramto.com * */ public class FileSetWritableExample < public static void main(String[] args) < File newFile = new File("src/main/java/com/javaprogramto/files/readonlywrite/make-read-only.txt"); // Changing the file from read only to writable format. boolean isWritableNow = newFile.setWritable(true); System.out.println("Can write the file ? : " + isWritableNow); >>
Can write the file ? : true
5. Conclusion
In this article, we’ve seen how to change file permissions from read only to writable and writable to read only in java with examples.
Labels:
SHARE:
About Us
Java 8 Tutorial
- Java 8 New Features
- Java 8 Examples Programs Before and After Lambda
- Java 8 Lambda Expressions (Complete Guide)
- Java 8 Lambda Expressions Rules and Examples
- Java 8 Accessing Variables from Lambda Expressions
- Java 8 Method References
- Java 8 Functional Interfaces
- Java 8 — Base64
- Java 8 Default and Static Methods In Interfaces
- Java 8 Optional
- Java 8 New Date Time API
- Java 8 — Nashorn JavaScript
Java Threads Tutorial
Kotlin Conversions
Kotlin Programs
Java Conversions
- Java 8 List To Map
- Java 8 String To Date
- Java 8 Array To List
- Java 8 List To Array
- Java 8 Any Primitive To String
- Java 8 Iterable To Stream
- Java 8 Stream To IntStream
- String To Lowercase
- InputStream To File
- Primitive Array To List
- Int To String Conversion
- String To ArrayList
Java String API
- charAt()
- chars() — Java 9
- codePointAt()
- codePointCount()
- codePoints() — Java 9
- compareTo()
- compareToIgnoreCase
- concat()
- contains()
- contentEquals()
- copyValueOf()
- describeConstable() — Java 12
- endsWith()
- equals()
- equalsIgnoreCase()
- format()
- getBytes()
- getChars()
- hashcode()
- indent() — Java 12
- indexOf()
- intern()
- isBlank() — java 11
- isEmpty()
- join()
- lastIndexOf()
- length()
- lines()
- matches()
- offsetByCodePoints()
- regionMatches()
- repeat()
- replaceFirst()
- replace()
- replaceAll()
- resolveConstantDesc()
- split()
- strip(), stripLeading(), stripTrailing()
- substring()
- toCharArray()
- toLowerCase()
- transform() — Java 12
- valueOf()
Spring Boot
$show=Java%20Programs
$show=Kotlin
accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content
Making a File Read-Only in Java
Learn to create a new file and make the file read-only in Java. A read-only file can be opened for reading, but we cannot modify or delete the file contents. A read-only file or directory can be deleted if the file system permits.
The setReadOnly() method marks the file or directory specified in the path so that only read operations are allowed.
The method returns true if and only if the operation succeeded; false otherwise
File file = new File("c:/temp/testReadOnly.txt"); // Mark it read only boolean success = file.setReadOnly();
2. Using File.setWritable(false)
The setWritable() is a convenient method to set the owner’s write permission for this abstract pathname.
It returns true if the operation succeeded. The operation will fail with SecurityException if the user does not have the required permissions.
File file = new File("c:/temp/testReadOnly.txt"); // Mark it read only boolean success = file.setWritable(false);
3. Check if the File is Read-Only or Writable
In order to check if the file is writable or read-only, we can use canWrite() method of File class. This method returns:
File file = new File("c:/temp/testReadOnly.txt"); System.out.println("File is writable : " + file.canWrite()); // true // Mark it read only boolean success = file.setWritable(false); System.out.println("File is writable : " + file.canWrite()); // false
How to make a File Read Only in Java
Making a file read only is very easy in java. In this tutorial, we will learn following three things.
1) How to make a file read only
2) How to check whether the existing file is in read only mode or not
3) How to make a read only file writable in java.
1) Changing file attributes to read only
To make a file read only, we can use setReadOnly() method of File class. It returns a boolean value which we can further use to verify whether the operation got successful or not, same way as I did in the below program. As you can see that in the below program, I am changing the file attributes to read only of file “Myfile.txt” which is present in “C drive” of my computer.
import java.io.File; import java.io.IOException; public class ReadOnlyChangeExample < public static void main(String[] args) throws IOException < File myfile = new File("C://Myfile.txt"); //making the file read only boolean flag = myfile.setReadOnly(); if (flag==true) < System.out.println("File successfully converted to Read only mode!!"); >else < System.out.println("Unsuccessful Operation!!"); >> >
File successfully converted to Read only mode!!
2) Check whether the file is writable or read only
In order to check the file attributes, we can use canWrite() method of file class. This methods returns true if the file is writable else it returns false. As I am performing the operation on the file “Myfile.txt” which I already set to read only in the previous program, I am getting output as “File is read only”.
import java.io.File; import java.io.IOException; public class CheckAttributes < public static void main(String[] args) throws IOException < File myfile = new File("C://Myfile.txt"); if (myfile.canWrite()) < System.out.println("File is writable."); >else < System.out.println("File is read only."); >> >
3) How to make a read only file writable in java
To make a read only file to writable file, we can use setWritable() method. This method can also be used to make a file read only.
file.setWritable(true) : To make file writable.
file.setWritable(false) : To make file read only.
import java.io.File; import java.io.IOException; public class MakeWritable < public static void main(String[] args) throws IOException < File myfile = new File("C://Myfile.txt"); //changing the file mode to writable myfile.setWritable(true); if (myfile.canWrite()) < System.out.println("File is writable."); >else < System.out.println("File is read only."); >> >