Following example demonstrates, how to create and write a file. In the example subclasses of Writer abstract class are used to write on file.
Java write file
Following example demonstrates, how to create and
write a file. In the example subclasses of Writer abstract class
are used to write on file.
File class is public and found under
java.io
package. This class extends Object class
which is the root of the class hierarchy.
In the example with File class, several character files are created.
And as shown in the example these files are written by the objects methods of
subclasses of abstract writer class.
Write_File. java
import java.io.*; public class Write_File { public static void main(String args[]) throws IOException { File flt = new File("codingdiary.doc"); FileWriter wrt = new FileWriter(flt); CharSequence cq = "welcome to future"; wrt.append(cq); wrt.flush(); System.out.println("Output is generated in a file codingdiary.doc"); flt = new File("roseindia.txt"); PrintWriter out = new PrintWriter(new BufferedWriter( new FileWriter(flt))); out.print("Welcome to roseindia.net"); out.flush(); System.out.println("Output is generated in a file roseindia.txt"); flt = new File("rachel_weisz"); flt.createNewFile(); System.out.println("An unknown extension file rachel_weisz is created"); CharArrayWriter ch = new CharArrayWriter(); cq = "newstrackindia.com"; ch.append(cq); ch.flush(); System.out.println(ch.toString()); } } |