Saturday, May 12, 2012

Write String to File using Java

It's a simple example to write String to text file using Java code. Please note that you need the right to write in the target file.

package javafile;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class WriteStringToFile {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        FileWriter fileWriter = null;
        try {
            String content = "Hello! Java-Buddy :)";
            File newTextFile = new File("C:/test/test.txt");
            fileWriter = new FileWriter(newTextFile);
            fileWriter.write(content);
            fileWriter.close();
        } catch (IOException ex) {
            Logger.getLogger(WriteStringToFile.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                fileWriter.close();
            } catch (IOException ex) {
                Logger.getLogger(WriteStringToFile.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}


Related:
- Save file with JavaFX FileChooser


3 comments:

  1. thats great, can you upload the code for creating .pdf,.doc files etc in JAVA

    ReplyDelete
  2. Logger.getLogger(WriteStringToFile.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
    try {
    fileWriter.close();
    } catch (IOException ex) {
    Logger.getLogger(WriteStringToFile.class.getName()).log(Level.SEVERE, null, ex);

    ReplyDelete
  3. Every time when we invoke the program with new strings, it should add (not overwrite) the strings into that file for this condition what we need to add in the above pgm

    ReplyDelete