我对Java不是特别精通。
我将一个字节数组转换为字符串(每个字节都有一个十进制表示),然后写入一个文件。下面是一个最小的例子,它再现了我遇到的问题(我已经把文件命名的东西放在里面了,以防它相关):
public class PacketWriter {
public static void writeBytes(byte[] in) {
Calendar cal = Calendar.getInstance();
cal.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("ddmmyyHHmmss");
PrintStream out = null;
File outFile = null;
try {
outFile = new File("recpacket"+sdf.format(cal.getTime())+".txt");
outFile.createNewFile(); // also checks for existence of file alre ady
out = new PrintStream(new FileOutputStream(outFile,false));
System.out.println(Arrays.toString(in));
out.print(Arrays.toString(in));
out.flush();
System.out.println("Did the writing!");
} catch (FileNotFoundException e) {
System.err.println("Packet output file not found.");
} catch (IOException e) {
System.err.println("Could not write packets (I/O error).");
}
finally {
System.out.println("Closing...");
if (out != null) out.close();
System.out.println("Closed.");
}
}
}
当我呼叫PacketWriter.writeBytes(/* some nonempty byte array */)
时我得到以下输出:
... array ...
Did the writing!
Closing...
JVM_Close returned -1
Closed.
写入stdout。
该文件在返回时为空,并且不包含我希望它包含的字符串。
怎么了?
PrintStream
类的错误报告非常糟糕:看起来写入文件失败了,但不可能知道原因;例如,这可能是因为文件系统中没有剩余空间。尝试使用FileWriter
:
Writer out = null;
out = new FileWriter(outFile,false);
System.out.println(Arrays.toString(in));
out.write(Arrays.toString(in));
out.flush();