Java Reference
In-Depth Information
// Allocate the bytes for the record and read it,
byte [] record = new byte[recLen];
file.read(record);
// Close the file.
file.close();
E XERCISES
Now it's time to try out what you've learned with some simple examples.
1. Edit the HelloWorld Java program you've been working with and remove
the code from the main() method. You will need to import the java.io pack-
age in order to compile and run this example.
import java.io.*;
2. First, let's create a File object referring to a file called myfile.dat in the cur-
rent working directory.
// Create a File object.
File file = new File("myfile.dat");
3. You'll check for the existence of this file. It won't exist the first time you
run the program.
// Check for existence of file.
if (file.exists())
System.out.println("File exists");
else
System.out.println("File does not exist");
4. You're going to write raw bytes to this file. You will have to bracket this
code with a try...catch block because you could get an exception.
try
{
// Create output stream to write to file.
FileOutputStream ostrm = new FileOutputStream(file);//
Write bytes to file from a String.
for (int i = 0; i < 20; i++)
{
Search WWH ::




Custom Search