gpt4 book ai didi

java - 关闭 BufferedWriter 会删除写入文件的所有文件数据吗?

转载 作者:行者123 更新时间:2023-12-01 10:10:03 28 4
gpt4 key购买 nike

我从 ObjectInputStream 获取连续数据,我正在使用 BufferedWriter 对象将其写入文件。我正在检查文件大小不断增加。现在,一旦我停止用 false 停止 while(true) 方法,该方法继续运行该方法,我就会关闭我的 BufferedWriter 对象。执行此操作后,写入文件的所有数据都会丢失。

private void appendFile(JLabel jLab0x28, Socket client)
{
try
{
if(!continueMe)
{
fileOut.close();
fileOut = null;
in.close();
System.gc();
jLab0x28.setText("<html> <font color='red'> Socket is closed "+client.isClosed()+" </font> </html>");
System.out.println("File size after discontinuing "+
humanReadableByteCount(new File("C:\\ISSUE124_Resolved.txt").length(), true) );
}

if(!client.isClosed())
{
try
{
String data = in.readObject().toString();
System.out.println("File size is "+
humanReadableByteCount(new File("C:\\ISSUE124_Resolved.txt").length(), true) );
fileOut.append(data);
fileOut.flush();
}
catch (EOFException exp)
{
continueMe = true;
exp.printStackTrace();
System.out.println("A Stream has finished "+exp.toString()+"\n");
}
catch (ClassNotFoundException exp)
{
exp.printStackTrace();
System.err.println(exp.toString());
continueMe = false;
}
}
}
catch(IOException exp)
{
try
{
fileOut.close();
}
catch (IOException e)
{
e.printStackTrace();
}
exp.printStackTrace();
System.err.println("Exception "+exp.toString());
jLab0x28.setText(exp.getMessage());
continueMe = false;
}
}
public static String humanReadableByteCount(long bytes, boolean si) {
int unit = si ? 1000 : 1024;
if (bytes < unit) return bytes + " B";
int exp = (int) (Math.log(bytes) / Math.log(unit));
String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp-1) + (si ? "" : "i");
return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
}

记录的数据:

File size is  118.3 kB
File size is 118.4 kB
File size is 118.5 kB
File size is 118.7 kB
File size is 118.8 kB
File size is 118.9 kB
File size is 119.1 kB
File size is 119.2 kB
File size is 119.3 kB
Done
Closed Socket connection from client
File size after discontinuing 0 B

最佳答案

您需要关闭输出流。目前,您正在 catch 子句中执行此操作,如果您没有遇到 IOException (并且您不希望出现这种情况),则不会到达该子句

catch(IOException exp)
{
try
{
fileOut.close();
}
...

像这样修改你的代码

catch(IOException exp)
{

exp.printStackTrace();
System.err.println("Exception "+exp.toString());
jLab0x28.setText(exp.getMessage());
continueMe = false;
}
try
{
fileOut.close();
}
catch (IOException e)
{
e.printStackTrace();
}

关于java - 关闭 BufferedWriter 会删除写入文件的所有文件数据吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36177757/

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