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()); } } |
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.
Ask Questions? Discuss: Java write file
Post your Comment