Intro
This examples, will demonstrates how to write a simple file using String contents. To write this file, you can use FileWriter class.
Examples
package com.freesamplecode.java.io;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WriteFileDemo {
public static void main(String[] args) {
String contents = "This is a content will be append in the file";
File file = new File("D:/temp/testfile.txt");
FileWriter fw = null;
try {
if (!file.exists()) {
file.createNewFile();
}
fw = new FileWriter(file);
fw.write(contents);
fw.close();
System.out.println("File "+file.getAbsolutePath() + " has been successfully created");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
if(fw != null){
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Output
File D:\temp\testfile.txt has been successfully created

0 comments: