gpt4 book ai didi

java - 无法在 Filewriter 上获取 "append mode"为我工作

转载 作者:行者123 更新时间:2023-12-01 23:54:33 26 4
gpt4 key购买 nike

我进行了各种搜索,似乎给出的答案对我不起作用。

我的代码相对简单,它生成一个对象数组,用一些随机字符串填充它,然后尝试输出到文件。这个想法基本上是生成一个包含一些名称、登录名、密码等的 CSV 文件,这些名称是随机字母的字符串(长话短说,它是为了大量填充用户的环境......)

我有一个像这样的“Writer”类:

    public class Writer {
public static void log(String message) throws IOException {

PrintWriter out = new PrintWriter(new FileWriter("testlog.txt"), true);
out.println(message);

out.close();
}
}

像这样的循环:

    for (int y=0; y < num_names; y++) {
try {
Writer.log(arrayTest[y].first + "," + arrayTest[y].last + "," + arrayTest[y].loginName + "," + arrayTest[y].password +
"," + arrayTest[y].email);
} catch (IOException ex) {
Logger.getLogger(Csvgenerator.class.getName()).log(Level.SEVERE, null, ex);
}


System.out.println(arrayTest[y].first + "," + arrayTest[y].last + "," + arrayTest[y].loginName + "," + arrayTest[y].password +
"," + arrayTest[y].email);

}

我的期望是我将循环遍历,并且对于 arrayTest[] 中的每个对象,我将一行数据输出到文件中。我包含 System.out.println 只是为了调试。

当我运行代码时,System.out.println 证明它工作正常——我得到了 10 行的列表。 (此处 num_names = 10)因此这证明每次我到达这行代码时,我都会打印出唯一的“行”数据。

但是,在运行结束时,文件“teSTLog.txt”仅包含一行——输出中的最后一行。

我尝试过“out.append”而不是“out.println”,但没有区别。似乎每次我调用记录器时,它都会出于某种原因重新创建文件。

换句话说,如果我的控制台输出(来自 system.out.println)如下所示:

nxoayISPaX,aNQWbAjvWE,nanqwbajvwe,P@ssw0rd!,nanqwbajvwe@mylab.com
RpZDZAovgv,QOfyNRtIAN,rqofynrtian,P@ssw0rd!,rqofynrtian@mylab.com
SajEwHhfZz,VziPeyXmAc,svzipeyxmac,P@ssw0rd!,svzipeyxmac@mylab.com
sifahXTtBx,MRmewORtGZ,smrmewortgz,P@ssw0rd!,smrmewortgz@mylab.com
PlepqHzAxE,MQUJsHgEgy,pmqujshgegy,P@ssw0rd!,pmqujshgegy@mylab.com
VKYjYGLCfV,nuRKBJUuxW,vnurkbjuuxw,P@ssw0rd!,vnurkbjuuxw@mylab.com
YgvgeWmomA,ysKLVSZvaI,yysklvszvai,P@ssw0rd!,yysklvszvai@mylab.com
feglvfOBUX,UTIPxdEriq,futipxderiq,P@ssw0rd!,futipxderiq@mylab.com
RAQPPNajxR,vzdIwzFHJY,rvzdiwzfhjy,P@ssw0rd!,rvzdiwzfhjy@mylab.com
DeXgVFClyg,IEuUuvdWph,dieuuuvdwph,P@ssw0rd!,dieuuuvdwph@mylab.com

那么teSTLog.txt只包含一行:

DeXgVFClyg,IEuUuvdWph,dieuuuvdwph,P@ssw0rd!,dieuuuvdwph@mylab.com

如何强制它继续使用同一文件并仅附加新行?

最佳答案

在构造函数PrintWriter(Writer out, boolean autoFlush)上,第二个 boolean 参数实际上用于自动刷新,而不是附加模式。

我认为您打算改用 FileWriter(File file, boolean append) 构造函数,即:

PrintWriter out = new PrintWriter(new FileWriter("testlog.txt", true));

而不是

PrintWriter out = new PrintWriter(new FileWriter("testlog.txt"), true);

关于java - 无法在 Filewriter 上获取 "append mode"为我工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15798760/

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