JAVA Writing to a file with specific offset

。_饼干妹妹 提交于 2019-12-10 11:50:31

问题


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


    }

}

回答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.




回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/28913543/java-writing-to-a-file-with-specific-offset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!