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