Java: Write to a file

Append to a file using BufferedWriter

public static void bufferedWriter(String file, String text)
{
	try{
		BufferedWriter bw  = new BufferedWriter(new FileWriter(file, true)); // true means append to the file
		bw.write(text);
		bw.close();
	}catch(Exception e)
	{
		e.printStackTrace();
	}
}

Append to a file using PrintWriter

public static void printWriter(String file, String text)
{
	try{
		PrintWriter pw = new PrintWriter(new FileWriter(file,true)); // true means append to the file
		pw.write(text);
		pw.close();
	}catch(Exception e){
		e.printStackTrace();
	}
}

Overwrite a file using PrintWriter

public static void overwrite(String file, String[] text)
{
	try{
		PrintWriter pw = new PrintWriter(new FileWriter(file)); // without the true param, it overwrites the file
		for(String t:text)
		{
			pw.write(t);
		}
		pw.close();
	}catch(Exception e){
		e.printStackTrace();
	}
}

All together.

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintWriter;

public class WriteToFile {
	
	public static void bufferedWriter(String file, String text)
	{
		try{
			BufferedWriter bw  = new BufferedWriter(new FileWriter(file, true)); // true means append to the file
			bw.write(text);
			bw.close();
		}catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	
	public static void printWriter(String file, String text)
	{
		try{
			PrintWriter pw = new PrintWriter(new FileWriter(file,true)); // true means append to the file
			pw.write(text);
			pw.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public static void overwrite(String file, String[] text)
	{
		try{
			PrintWriter pw = new PrintWriter(new FileWriter(file)); // without the true param, it overwrites the file
			for(String t:text)
			{
				pw.write(t);
			}
			pw.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public static void main(String args[])
	{
        String text[]={"hey, what's up", "Nothing much."};
        for(String t: text)
        {
        	bufferedWriter("src/basics/files/greeting.txt",t);
        	printWriter("src/basics/files/greeting.txt",t);
        }
        overwrite("src/basics/files/greeting.txt",text);
	}
}

Search within Codexpedia

Custom Search

Search the entire web

Custom Search