gpt4 book ai didi

java - 将数据 append 到同一文件

转载 作者:行者123 更新时间:2023-12-02 11:22:43 27 4
gpt4 key购买 nike

将数据 append 到同一文件时遇到问题,尽管尝试过但出现错误。

这是我的代码

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

}
}
}

这是错误。我的输出文件指向数据输出文件,但它仍然无法将其 append 。

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

最佳答案

我已经自己解决了这个问题 - 这就是答案。我正在做的是 - 在第 7 行我创建了指向文件“dataoutput.txt”的“bw”,在第 19 行我创建了指向同一个文件的“fw”,并且文件在 7 处打开。所以,我更改了它改为 pw,这工作正常 - 我能够将数据 append 到文件中。

{
private static final String INPUT_FILE =
"C:\\PowerShell Automation\\data.txt";
private static final String OUTPUT_FILE =
"C:\\PowerShell Automation\\dataoutput.txt";

public static void main( String args[] ) throws IOException {
URLShortener u = new URLShortener( 100, "https://is.gd/" );

System.out.println( "Appending new data to shortUrls" );

try( BufferedReader br = new BufferedReader(
new InputStreamReader( new FileInputStream( new File(
INPUT_FILE ) ) ) );
// *** open for append
PrintWriter pw = new PrintWriter( new FileWriter(
OUTPUT_FILE, true ) );
)
{
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 ) ) );

pw.println( shortenedUrl );
}
}
}

关于java - 将数据 append 到同一文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49810498/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com