【发布时间】:2016-03-23 12:06:44
【问题描述】:
我从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
【问题讨论】:
-
如果你不发
humanReadableByteCount代码很难知道... -
它只是一个返回文件大小的代码。立即检查更新的问题
-
代码看起来也很可疑。将
Socket作为这样的参数传递......这不好。 -
我知道,但这不会造成问题。我刚刚使用了 FileWriter 并且它工作正常。
标签: java bufferedwriter objectinputstream