Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple stream read/write question in java

Tags:

java

io

I'm trying to upload a file via URLConnection, but I need to read/write it as a binary file without any encoding changes.

So i've tried to read byte[] array from a FileInputStream, but now i have an issue. The PrintWriter object I use for outputing to the server does not allow me to do writer.write(content) (where content is of type byte[]). How can i fix this? Or is there another way to quickly copy binary data from a FileInputStream to a PrintWriter?

Thank you

like image 407
Marius Avatar asked Dec 23 '22 04:12

Marius


1 Answers

I bet that this is an follow-up on this question: Upload files from Java client to a HTTP server

If you want to upload binary files as well using multipart/form-data, then you need to write them to the OutputStream instead. Here's the changed example of the code as I posted in your previous example, only the try block has been changed to keep a separate handle to the binary output stream, so that you can write any InputStreams to it without any encoding pains:

OutputStream output = null;
PrintWriter writer = null;
try {
    output = connection.getOutputStream();
    writer = new PrintWriter(new OutputStreamWriter(output, "UTF-8"), true); // true = Autoflush, important!

    writer.println("--" + boundary);
    writer.println("Content-Disposition: form-data; name=\"paramToSend\"");
    writer.println("Content-Type: text/plain; charset=UTF-8");
    writer.println();
    writer.println(paramToSend);

    writer.println("--" + boundary);
    writer.println("Content-Disposition: form-data; name=\"fileToUpload\"; filename=\"" + fileToUpload.getName() + "\"");
    writer.println("Content-Type: " + URLConnection.guessContentTypeFromName(fileToUpload.getName());
    writer.println("Content-Transfer-Encoding: binary");
    writer.println();
    InputStream input = null;
    try {
        input = new FileInputStream(fileToUpload);
        byte[] buffer = new byte[1024];
        for (int length = 0; (length = input.read(buffer)) > 0;) {
            output.write(buffer, 0, length);
        }
        output.flush();
    } finally {
        if (input != null) try { input.close(); } catch (IOException logOrIgnore) {}
    }
    writer.println();

    writer.println("--" + boundary + "--");
} finally {
    if (writer != null) writer.close();
}
like image 123
BalusC Avatar answered Dec 26 '22 00:12

BalusC