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