jdaues
asked on
file.write...IndexOutOfBoundsException
What is causing the exception to be thrown and how do I fix it?
public static void main(String[] args)
{
try
{
FileOutputStream file = new FileOutputStream ("testfile.txt");
byte[] buffer = "this is string 1".getBytes(); // convert String to byte[]
int offset = 0;
file.write(buffer, // buffer
offset, // offset
buffer.length); // length
offset += buffer.length; // add length of what we just wrote to offset
buffer = "this is string 2".getBytes(); // convert String to byte[]
System.out.println ("Everything OK so far...");
file.write(buffer, // buffer
offset, // offset
buffer.length); // length
}
catch (Exception e)
{
// throws java.lang.IndexOutOfBounds Exception
System.out.println("Except ion: " + e.toString());
}
}
public static void main(String[] args)
{
try
{
FileOutputStream file = new FileOutputStream ("testfile.txt");
byte[] buffer = "this is string 1".getBytes(); // convert String to byte[]
int offset = 0;
file.write(buffer, // buffer
offset, // offset
buffer.length); // length
offset += buffer.length; // add length of what we just wrote to offset
buffer = "this is string 2".getBytes(); // convert String to byte[]
System.out.println ("Everything OK so far...");
file.write(buffer, // buffer
offset, // offset
buffer.length); // length
}
catch (Exception e)
{
// throws java.lang.IndexOutOfBounds
System.out.println("Except
}
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
offset is the length of the first buffer.
if this + the length of the second buffer is greater than the length of the second buffer, then it'll throw that error.
public void write(byte[] b,
int off,
int len)
throws IOException
Writes len bytes from the specified byte array starting at offset off to this file output stream.