//This example illustrates how to read and write to a file using the RandomAccessFile class

import java.io.*;

public class RandomAccessFileExample
{
	public static void main(String [] args) throws IOException
	{
		String [] myArray = {"hello", "world", "goodbye", "java"};

		//stdin is only used for getting input from the keyboard
		BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));

		//get the filename
		System.out.print("Please enter a filename: ");
		String filename = stdin.readLine();

		//create the file		
		RandomAccessFile myFile = new RandomAccessFile(filename, "rw");
		
		//print out all the words to the file
		for (int i = 0; i < myArray.length; i++)
		{
			myFile.writeBytes(myArray[i] + "\n");
		}
		
		//goes back to the beginning of the file
		myFile.seek(0);
		
		//gets the size of the file and prints it out
		System.out.println("myFile.length() ==> " + myFile.length());

		//read the first line of the file
		String str = myFile.readLine();

		//the file still contains data while str is not null because myFile.readLine() returns data
		while (str != null)
		{
			System.out.println("Read from file => " + str);
			str = myFile.readLine(); 
		}
		
		//close file
		myFile.close();
	}
}
