JaVa
   

Writing Data to a File

Let's now look at a working example of how we could easily write a player's name and high score to a file in the same directory as we executed the code. Note that the player's name will be a string value and the score will be an integer.

Code Listing 6-3: Writing data to a file
import java.io.*;
public class SimpleWrite
{
 public SimpleWrite()
 {
 // Hard code the players name and score...
 String playerName = "George";
 int playerScore = 125;
 // Create out file object...
 File theFile = new File("output.txt");
 try
 {
 // Create a data output stream for the file...
 DataOutputStream outputStream = new DataOutputStream(new
 FileOutputStream(theFile));
 // Write the data to the output stream...
 // ->> the name...
 outputStream.writeUTF(playerName);
 // ->> the score
 outputStream.writeInt(playerScore);
 // Close the output stream...
 outputStream.flush();
 outputStream.close();
 }
 catch(IOException e)
 {
 System.out.println(e);
 }
 }
 public static void main(String args[])
 {
 SimpleWrite mainApp = new SimpleWrite();
 }
}


Java End example

When we run this console app, we can see that it has written a file called output.txt to the same directory from which the app was run. Here is how the file we write looks when we open it in Notepad:

Java Click To expand
Screenshot-3: How our output file looks

As you can see from the above image, the file we have written is not just plain text but is instead in binary format. Because of this, it makes it much easier to read information back from the file into Java, as we will see in the next example. For now though, let's look at how the code works to allow us to write the file. Start by creating two variables with information that we wish to write to the file: one a string value and the other just an integer value. This is done with the following two lines of code:

String playerName = "George";
int playerScore = 125;


Next we need to create a file object, which will create an empty file on the hard drive (or wherever you are trying to create it). In this example, we will create it in the same directory the app was executed from. We have called the file output.txt. (Remember that the file isn't actually a text file, but we have called it this so it is easy to look at in a text editor). To create our file object, use the following line of code:

File theFile = new File("output.txt");


The path that this file object relates to is the path where your main class is executed. Now that we have a file object, we can attempt to create a DataOutputStream using the FileOutputStream, to which we pass in our file. A DataOutputStream allows us to output data to wherever we have specified, which in this case is a file. Here is the line of code that we require to do this:

try
{
 DataOutputStream outputStream = new DataOutputStream(new
 FileOutputStream(theFile));


Note that an IOException can be thrown when trying to create the DataOutputStream, so we have encapsulated the whole next segment of code in a try/catch statement to catch the IOException. Next, write the player's name to the output stream. This is done by means of the writeUTF method, which writes the string in Unicode format. This can be seen in the following line of code:

outputStream.writeUTF(playerName);


Once we have our name output to the stream, we then output the player's score by utilizing the writeInt method of the output stream. This can be seen in the following code:

outputStream.writeInt(playerScore);


Note that there are variations of the write method for each of the different basic data types, as well as a method simply called write, which can be used to output an array of bytes to an output stream. We will look at some of these different methods in more examples later in this chapter. Once the data is written to the output stream, call the flush method of the output stream to ensure that all the data has been written. Then we finally call the close method to close our output stream. This can be seen in the following two lines of code:

outputStream.flush();
outputStream.close();


JaVa
   
Comments