gpt4 book ai didi

java - 文件输入输出追加

转载 作者:行者123 更新时间:2023-11-30 03:22:32 24 4
gpt4 key购买 nike

我正在尝试将一些坐标写入文件,然后将其作为字符串读取。所以我需要将它们写入附加文件......没有空格或换行,但我的代码只写入第一个坐标,即 pos_Let ,但不写入 pos_Num code> 根本没有,甚至没有空格或换行。

那么我怎样才能得到像这样写入文件 pos_LetposNum 的代码呢?显然我的意思是他们的引用文献;) ..提前致谢

protected  void writeCoordtoFile () throws IOException
{
File file = new File("FermiPresentCoord.txt");
boolean yes = file.createNewFile() ;
//boolean yes = exists();
if (yes == true)
{
// create a FileWriter Object
FileWriter writer = new FileWriter(file, true);

// Writes the content to the file
writer.write("");
writer.flush();
writer.write(pos_Let);
writer.flush();
writer.write(pos_Num);
writer.close();
}
else
{
// creates the file
file.createNewFile();

// creates a FileWriter Object
FileWriter out = new FileWriter(file);

// Writes the content to the file
out.write(pos_Let);
out.flush();
out.write(pos_Num);
out.flush();
out.close();
}
}

最佳答案

引用方法createNewFile() :

Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. The check for the existence of the file and the creation of the file if it does not exist are a single operation that is atomic with respect to all other filesystem activities that might affect the file.

Note: this method should not be used for file-locking, as the resulting protocol cannot be made to work reliably. The FileLock facility should be used instead.

Returns:true if the named file does not exist and was successfully created; false if the named file already exists

在您的情况下,您首先创建文件,并且 createNewFile() 返回 true,因此您转到 if block ,将该行附加到当前文件。然后,createNewFile() 返回 false,因为该文件存在!因此,您转到 else block ,然后从头开始重新创建文件...

所以,基本上,只需用 else 反转 if,并且不要调用 createNewFile() 两次...可能的更改(这样您就不会感到困惑)这是我的简单建议:

protected  void writeCoordtoFile () throws IOException
{
File file = new File("FermiPresentCoord.txt");
boolean fileDoesNotExist = file.createNewFile() ;
//boolean fileDoesNotExist = file does **not** exist!
if (fileDoesNotExist)
{
// create a FileWriter Object
FileWriter writer = new FileWriter(file);

// Writes the content to the file
writer.write(pos_Let);
writer.write(pos_Num);
writer.close();

}
else
{
// creates a FileWriter Object
FileWriter out = new FileWriter(file,true);

// Writes the content to the file
out.write(""); //not sure why you need that...
out.write(pos_Let);
out.write(pos_Num);
out.close();
}
}

关于java - 文件输入输出追加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31001078/

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