I have a piece of code –
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import org.eclipse.core.runtime.Platform;
public class RAF {
public static void main(String[] args) {
File file = new File("test.txt");
Scanner scanner;
try {
scanner = new Scanner(file).useDelimiter("\n");
String line = scanner.next();
String newLine = line.substring(0, 252) + "<input type=\"button\" value = \"abhishek\" />" + line.substring(252);
FileWriter writer = new FileWriter(file);
writer.write(newLine);
writer.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
and the test.txt file is –
> <!DOCTYPE html PUBLIC "-//W3C//DTD
> HTML 4.01 Transitional//EN"
> "http://www.w3.org/TR/html4/loose.dtd">
> <html> <head> <meta
> http-equiv="Content-Type"
> content="text/html;
> charset=ISO-8859-1"> <title>Insert
> title here</title> </head> <body>
>
> <form><input></form> </body> </html>
The total length of test.txt is 285 and I want to add the content at 252 location so that the output will be –
> "http://www.w3.org/TR/html4/loose.dtd">
> <html> <head> <meta
> http-equiv="Content-Type"
> content="text/html;
> charset=ISO-8859-1"> <title>Insert
> title here</title> </head> <body>
>
> <form>**<input type="button" value =
> "abhishek"/>**<input></form> </body>
> </html>
But I am getting exception –
Exception in thread “main” java.lang.StringIndexOutOfBoundsException: String index out of range: 252
at java.lang.String.substring(Unknown Source)
at com.lg.palette.elementEditFactory.RAF.main(RAF.java:25)
What is the problem with the code
My main objective is to get the content as shown in the 2nd test.txt
You’re only reading the first line of the file… which isn’t 252 characters long. It looks like you really want to read the whole file in and then modify it.
Guava has some useful methods in
Filesto read an entire file in one go.(In general this feels like a pretty fragile approach though… how confident are you that the split point will always be 252 characters into the HTML?)