Java Reference
In-Depth Information
String text = "This is text " + i;
byte [] bytes = text.getBytes();
ostrm.write(bytes);
}
// Close the output stream.
ostrm.close();
}
catch (Exception e)
{
System.out.println("You had a output problem:" + e);
}
5. Finally, you're going to check for the existence of the file again. If the code
executes properly, this time the file will exist.
// Check for existence of file.
if (file.exists())
System.out.println("File exists");
else
System.out.println("File does not exist");
6.
Let's compile this program and execute it. The output should look like this:
File does not exist
File exists
7. Let's enhance the program to read the data back that you write out to the
file. After the code you added, let's create an input stream. Once again, you
have to bracket the code with a try...catch block.
try
{
// Create input stream to read file.
FileInputStream istrm = new FileInputStream(file);
// Allocate bytes to hold data.
byte [] bytes = new byte[14];
int bytesRead = istrm.read(bytes);
while (bytesRead != -1)
{
// Convert bytes to string and read some more.
System.out.println(new String(bytes));
bytesRead = istrm.read(bytes);
}
Search WWH ::




Custom Search