【发布时间】:2018-09-23 10:19:08
【问题描述】:
将数据附加到同一个文件时遇到问题,虽然尝试过但出现错误。
这是我的代码
public static void main(String args[]) throws IOException {
URLShortener u = new URLShortener(100, "https://is.gd/");
try (BufferedReader br = new BufferedReader(
new InputStreamReader(new FileInputStream(new
File("C:\\data.txt"))));
BufferedWriter bw = new BufferedWriter(new
FileWriter("C:\\dataoutput.txt")))
{
String line;
while ((line = br.readLine()) != null) {
String shortenedUrl = u.shortenURL(line);
System.out.println(new String(
"URL:" + line + "\t" + shortenedUrl + "\tExpanded: " + u.expandURL(shortenedUrl)));
bw.write(shortenedUrl + "\r\n");
System.out.println("Appending new data to shortUrls");
try (FileWriter fw = new FileWriter("C:\\dataoutput.txt", true);
BufferedWriter bappend = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bappend))
{
pw.println(shortenedUrl + "\r\n");
} catch(IOException e) {
e.getMessage();
}
}
}
}
这是错误。我的输出文件指向数据输出文件,但它仍然无法追加。
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 0, end 10, length 0
at java.base/java.lang.String.checkBoundsBeginEnd(Unknown Source)
at java.base/java.lang.String.substring(Unknown Source)
at com.misc.tests.URLShortener.sanitizeURL(URLShortener.java:101)
at com.misc.tests.URLShortener.shortenURL(URLShortener.java:67
at com.misc.tests.URLShortener.main(URLShortener.java:151
【问题讨论】:
-
该错误与追加到同一个文件无关。错误在
String shortenedUrl = u.shortenURL(line);中报告 - 可能该行不是 URL? -
你读的是空行吗?
-
line 是 data.txt 文件中的一个字符串,我已经在从文件中获取数据的开头声明了它 - 并且该文件有数百万个 Url。我实际上正在使用下面 GITHUB 中的现有代码。然后我创建了一个测试方法来生成缩短网址。 gist.github.com/rakeshsingh/64918583972dd5a08012
-
我解决了 StringIndexOutOfBoundsException - 这是因为我的数据文件中有空行。我已经修好了。但是,我无法附加到文件中。出于某种原因 - 我只是无法将新数据添加到现有文件中。