JVM_Close returned -1 when closing PrintStream

152 Views Asked by At

I'm not particularly proficient with Java.

I'm converting an array of bytes to a String (each byte with a decimal representation) and then writing to a file. Here is a minimal example that reproduces the problem that I'm having (I've left the file naming stuff in, just in case it's related):

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.");
        }
    }
}

When I call PacketWriter.writeBytes(/* some nonempty byte array */) I get the following output:

... array ...
Did the writing!
Closing...
JVM_Close returned -1
Closed.

written to stdout.

The file is empty upon return and does not contain the string that I want it to.

What's going wrong?

1

There are 1 best solutions below

2
On

The PrintStream class has very poor error reporting: it looks like writing to the file is failing, but it's impossible to know why; it could be because there's no space left in the file system for example. Try using a FileWriter instead:

    Writer out = null;

        out = new FileWriter(outFile,false);
        System.out.println(Arrays.toString(in));
        out.write(Arrays.toString(in));
        out.flush();