简体   繁体   中英

JAVA Writing to a file with specific offset

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());      
                } 


    }

}

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.

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 (ie heey). So you should have a check in your code, that offset should always be less than sentence.length ie number of characters in it.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM