我对Java并不是特别熟练。
我正在将一个字节数组转换为一个String(每个字节都带有十进制表示),然后写入一个文件。这是一个最小的例子,它重现了我遇到的问题(我已经把文件命名为了,以防万一它与之相关):
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。
返回时文件为空,并且不包含我想要的字符串。
出了什么问题?
答案 0 :(得分:2)
PrintStream
类的错误报告非常糟糕:看起来写入文件失败了,但是不可能知道原因;这可能是因为例如文件系统中没有剩余空间。请尝试使用FileWriter
代替:
Writer out = null;
out = new FileWriter(outFile,false);
System.out.println(Arrays.toString(in));
out.write(Arrays.toString(in));
out.flush();