0

我对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.

写入标准输出。

该文件在返回时为空,并且不包含我想要的字符串。

怎么了?

4

1 回答 1

2

该类PrintStream的错误报告非常差:看起来写入文件失败,但不可能知道原因;例如,这可能是因为文件系统中没有剩余空间。尝试使用 aFileWriter代替:

    Writer out = null;

        out = new FileWriter(outFile,false);
        System.out.println(Arrays.toString(in));
        out.write(Arrays.toString(in));
        out.flush();
于 2013-08-01T13:44:03.600 回答