Writing a file in java

Here is the code to write a string to a file in java:

import java.io.*;
class WriteFile {
public static void main(String args[]) {
try{
String s="data to write in file";
File f=new File("a.txt");
FileWriter fwr= new FileWriter(f);
Writer wr= new BufferedWriter(fwr);
wr.write(s);
wr.close();
}
catch(IOException ie) {
System.out.print(ie);
}
catch(Exception e) {
System.out.print(e);
}
}
}

First make a reference to file to which you want to write the data:
File f=new File("a.txt");
Here, in place of .txt, we can use any file extension as .srt,.xml,.doc etc

Then, create a file writer,
FileWriter fwr= new FileWriter(f);

Then, make a writer to write to the file:
Writer wr= new BufferedWriter(fwr);

then, call write function and pass the string:
wr.write(s);
Always remember to close the writer, otherwise it won’t write to the file:
wr.close();

We have to catch the exceptions thrown by the API methods also. To know more about exceptions, go to Java Exceptions

Advertisements
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: