1

I have to write a program that reads a file and inserts some text given by the user through the console window. The location in which the text is inserted should also be given through the console window.

Below is my code, I am getting "String index out of range" after entering the sentence and offset.

Enter The Sentence: heey

Enter location: 5

String index out of range: 9 <-- this is the error ,

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.FileInputStream; 
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.util.Scanner;
import java.io.Writer;


class ReadPosition{ 
    public static void main(String args[])    {   
    try{       
        FileWriter Writer =
                new FileWriter("in.txt");
        @SuppressWarnings("resource")
        BufferedWriter bufferedWriter =
                new BufferedWriter(Writer);


        Scanner input= new Scanner(System.in);
        System.out.println("Enter The Sentence: ");
        String sentence = input.nextLine();  
        System.out.println("Enter location: ");
        int offset = input.nextInt();
        input.close();

        byte[] buffer = sentence.getBytes();
        int len = buffer.length;
        bufferedWriter.write(sentence, offset, len);

    }

    catch(Exception ex)     
                { 
                    System.out.println(ex.getMessage());      
                } 


    }

}

3 Answers 3

1

The line

bufferedWriter.write(sentence, offset, len);

means write out len characters from sentence starting at offset in sentence.

In other words offset is the position in the sentence not the position in the output file.

If you want to insert text in a file you need to write code to copy the file to a new file adding the text at the correct position during the copy.

Also you should not be using

@SuppressWarnings("resource")

to suppress the close missing warning - you do need to close your writer.

Sign up to request clarification or add additional context in comments.

2 Comments

I understand what you mean , thank you for helping me . but how can i correct the code so i can write the sentence in the output file ?!
If you want to insert the text rather than overwriting what follows you have to copy the file. So your code needs a complete rewrite.
1

Given is the method to write content at particular position.

Lets say my file is Test.txt and content is as follow

Hello 
How are you
Today is Monday

now you want to write "hi" after hello. So the offset for "hi" will be "5".

Method is :

filename = "test.txt";
offset = 5;
byte[] content = ("\t hi").getBytes();

private void insert(String filename, long offset, byte[] content) throws IOException {

RandomAccessFile r = new RandomAccessFile(filename, "rw");
RandomAccessFile rtemp = new RandomAccessFile(filename+"Temp", "rw");
long fileSize = r.length(); 
FileChannel sourceChannel = r.getChannel();
FileChannel targetChannel = rtemp.getChannel();
sourceChannel.transferTo(offset, (fileSize - offset), targetChannel);
sourceChannel.truncate(offset);
r.seek(offset);
r.write(content);
long newOffset = r.getFilePointer();
targetChannel.position(0L);
sourceChannel.transferFrom(targetChannel, newOffset, (fileSize - offset));
sourceChannel.close();
targetChannel.close();
rtemp.close();
r.close();

}

The output will be:

Hello hi
How are you
Today is Monday

Comments

0

That's because internally write method will call getchar api to get characters from offset (5) until offset + (sentence.length - offset) (9)

And you sentence is just 4 characters long (i.e. heey). So you should have a check in your code, that offset should always be less than sentence.length i.e. number of characters in it.

2 Comments

I don't understand what you mean , can you show me in the code ?!
see this and especially s.getChars(b, b + d, cb, nextChar); this is what it does and have tried to explain in my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.