Home > Tutorial > Java Write File Sample Code

Java Write File Sample Code

The sample Java code below is a good tutorial on how to write data to a file. The code writes to a file using both the FileWriter and PrintWriter classes. Java provides a handful of classes and methods for writing all types of data to a file.

Class Name Method Parameters Return Type Exceptions
PrintWriter write() String void none
PrintWriter close() none void none
FileWriter write() String void IOException
FileWriter close() none void IOException

Java Write File Source Code:

package com.jcd.java.tutorials;

import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;


public class JavaFileWriter {

	 public static void main( String[] args )
	 {
		String sampleFileOut = "C:\\Users\\Admin\\Documents\\SampleFileOut.txt";
		
		try 
		{
			File myFile = new File(sampleFileOut);
			
			//Write to File using PrintWriter option
			writeFilePW(myFile, "Write this line using PrintWriter option.");
			
			//Write to File using FileWriter option
			writeFileFW(myFile, "Write this line using FileWriter option.");
			
		}
		catch(Exception ex)
		{
			System.out.println("Exception:"+ex.toString());
		}
	}
	 
	//PrintWriter Option
	public static void writeFilePW(File file, String data) 
	{
		try 
		{
			PrintWriter printWriter = new PrintWriter(file);
			
			//Write the data
			printWriter.write(data);
			
			//Write a new line
			printWriter.write("\r\n");
			
			//Close handle
			printWriter.close();
			
		}
		catch(Exception ex)
		{
			System.out.println("Exception:"+ex.toString());
		}
		
	}
	
	
	//FileWriter Option
	public static void writeFileFW(File file, String data) 
	{
		try 
		{
			FileWriter fileWriter = new FileWriter(file, true);
			
			//Write the data
			fileWriter.write(data);
			
			//Write a new line
			fileWriter.write("\r\n");
			
			//Close the handle
			fileWriter.close();
			
		}
		catch(Exception ex)
		{
			System.out.println("Exception:"+ex.toString());
		}
	}
	 
}



Java FileWriter Sample Code Output:



Java References:

Seymour
Posted by

Seymour

I have been a software developer for twenty years now focusing on writing high quality Java applications. If you are in a programming field, you know that technology is constantly changing. You have to keep current or you will get left behind!

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

Copyright © 2018 JavaCodeDepot