Home Java Examples Io Java Write To File From String
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Java Write To File From String

Advertisement
In this tutorial you will learn how to write to file from string. Write to file from string using java at first we will have to first create a file using the File (in case of the file is not existed) and then pass the file object or file name (in case of the existing file) to the FileWriter instance to write the character-stream.

Java Write To File From String

In this tutorial you will learn how to write to file from string.

Write to file from string using java at first we will have to first create a file using the File (in case of the file is not existed) and then pass the file object or file name (in case of the existing file) to the FileWriter instance to write the character-stream. You can also passed the FileWriter object to the higher level output stream instance such as BufferedWriter, PrintWriter to write efficiently.

Here I am going to give a simple example in which I have created a new text file using the File constructor and then pass this file object to the FileWriter instance to write characters into the file. Next I have passed the FileWriter object to the BufferedWriter instance which write method writes the characters more efficiently.

Example :

WriteFileFromString.java

import java.io.File;
import java.io.BufferedWriter;
import java.io.FileWriter;

class WriteFileFromString
 {
    public static void main(String args[])
     {
        String str = "This example demonstrates you how to write a file from string";
        File file = null;
        try
         {
            file = new File("writeToFileFromString.txt");
            BufferedWriter bw = new BufferedWriter(new FileWriter(file));
            bw.write(str);
            bw.close();
         }
        catch(Exception e)
          {
             System.out.println(e);
          }
       System.out.println("String is written into file successfully");
     }
 }

How to Execute this example :

After doing the basic process to execute a java program write simply on command prompt as :

javac WriteFileFromString.java to compile the program

And after successfully compilation to run simply type as :

java WriteFileFromString

Output :

When you will execute this example a text file will be created on the specified place as the path given by you with containing the text that you are trying to write in that file by java program like as :

Download Source Code

Advertisements

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: January 19, 2012

Ask Questions?    Discuss: Java Write To File From String  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com