Java gives a flexibility to read / write the contents(plain text) of a text file, even we can change the permission of text file using the code.
Let's see the implementation.
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class FileHandle1 { public static void main(String[] args) throws IOException { File file = new File("test.txt"); /*if (file.exists()) { file.delete(); } file.createNewFile();*/ //set to read only file.setReadOnly(); System.out.println("Before. canWrite?" + file.canWrite()); // set to writable file.setWritable(true); System.out.println("After. canWrite?" + file.canWrite()); //FileWriter f = new FileWriter(file,true); //append FileWriter f = new FileWriter(file); BufferedWriter b = new BufferedWriter(f); b.write("Sunil"); b.newLine(); //b.write("Sunil \n");// \n moves cursor to new line b.write("Kumar"); b.flush(); System.out.println("DOne"); String str=null; FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); System.out.println(br.read()); while((str=br.readLine())!=null) { System.out.println(br.readLine()); } } }
No comments:
Post a Comment