Link to home
Start Free TrialLog in
Avatar of jdaues
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.IndexOutOfBoundsException
   System.out.println("Exception: " + e.toString());
   }
}
Avatar of bobbit31
bobbit31
Flag of United States of America image

in your second file write,

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.

ASKER CERTIFIED SOLUTION
Avatar of bobbit31
bobbit31
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial