我正在使用ObjectInputStream
对象获取我在我的文件上写的连续数据BufferedWriter
。我正在检查文件大小不断增加。现在,一旦我停止使用while(true)
false
方法继续运行此方法,我将关闭我的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
答案 0 :(得分:1)
您需要关闭输出流。目前你正在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();
}
答案 1 :(得分:0)
好的,这里我使用了BufferedWriter的FileWriter对象intsead,现在我的文件数据没有被删除。所有的代码都是一样的,只是对象的改变才对我有所帮助。
await Task.Run(() =>
{
while(true
{
//Read your BT stream
}
});