0

Can someone explain me why I get: java.lang.StringIndexOutOfBoundsException: String index out of range: 5

File file = new File("file.txt");
    BufferedWriter writer = null;
    Date date;
    SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd");
    try { writer = new BufferedWriter(new FileWriter(file));        
            writer.write(" ",0,1);
            writer.write("FICH", 1, 4);
            writer.write("1234", 5, 4);
            writer.close();
        System.err.println(writer.toString());
    } 
    catch (IOException ex) {
        Logger.getLogger(FicheroTdALogic.class.getName()).log(Level.SEVERE, null, ex);
    }

    finally {
           try {writer.close();} catch (Exception ex) {}
        }
user3637887
  • 73
  • 1
  • 5
  • possible duplicate of [What is a stack trace, and how can I use it to debug my application errors?](http://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it-to-debug-my-application-errors) – Raedwald Sep 17 '14 at 12:47

1 Answers1

0

BufferedWriter.write() takes a string, offset and length. Offset tells the first character to write, length tells the count (how many).

Character indices are 0-based. The first character has an index of 0, the 2nd has an index of 1 etc.

So obviously in a string of "FICH" is 4 characters, valid indices are 0..3 inclusive. offset = 1 and length = 4 results in the last char being 5 which is out of bounds (illegal character index).

Similarly "1234" has valid indices 0..3 inclusive, even the offset is out of bounds (5) and also the last char (which would be at 9).

If you just want to write a whole String, don't pass anything else:

writer.write("Whole string will be written.");

If you need just a part of it, properly specify offset and length:

writer.write("Hello", 1, 3); // Writes "ell"
icza
  • 389,944
  • 63
  • 907
  • 827