【发布时间】:2011-08-13 19:52:14
【问题描述】:
我有一段代码-
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();
}
}
}
test.txt 文件是 -
> <!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>
test.txt 的总长度是 285,我想在 252 位置添加内容,这样输出将是 -
> "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>
但我得到了例外 - 线程“主”java.lang.StringIndexOutOfBoundsException 中的异常:字符串索引超出范围:252 在 java.lang.String.substring(未知来源) 在 com.lg.palette.elementEditFactory.RAF.main(RAF.java:25)
代码有什么问题 我的主要目标是获取第二个 test.txt 中显示的内容
【问题讨论】:
标签: java inputstream java.util.scanner