4Nikos
11/16/2018 - 11:23 PM

Java Writing and Reading file content

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;

public class Temp {

public static void main(String[] args) {
//------------------------------------------------------------
//define the variables and objects
	BufferedReader reader;
	FileWriter writer;
	String fileContentsRead = "";
	
//attempting to run code with the chance for an error
	try {
		//open the file for writing
		writer = new FileWriter ("story.txt");
		// write the letter "a" inside the file
		writer.write("Try changing the text being written to the file.");
		//closing the file (finish writing)
		writer.close();
		
		//opening file for reading
		reader = new BufferedReader (new FileReader("story.txt"));
		String line;

		while ((line = reader.readLine()) != null) {
			fileContentsRead = fileContentsRead + line;
		}
		//close the file (finished reading)
		reader.close();
	}
	//catch error happened in the try block
	catch(Exception e) {
		//print the stack trace (error) to the console
		e.printStackTrace();
	}
	finally {
		System.out.println(fileContentsRead);
	}
	
	
//------------------------------------------------------------
	}
}