[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 434
  • Last Modified:

URLConnection Binary Transfer

Basically I'm looking to transfer files from a URLConnection object to a file.  Although ASCII transfers fine over this method I get a few off characters in transferring a binary file (ie: a jpg image) giving the following output...

C:\>comp file1.jpg file1real.jpg
Compare error at OFFSET 123
file1 = 3F
file2 = 81
Compare error at OFFSET 581
file1 = 3F
file2 = 8F
Compare error at OFFSET 58E
file1 = 3F
file2 = 8F
Compare error at OFFSET 59B
file1 = 3F
file2 = 8F
Compare error at OFFSET 5A0
file1 = 3F
file2 = 81
Compare error at OFFSET 656
file1 = 3F
file2 = 90
Compare error at OFFSET 666
file1 = 3F
file2 = 8F
Compare error at OFFSET 7D9
file1 = 3F
file2 = 81
Compare error at OFFSET AE9
file1 = 3F
file2 = 81
Compare error at OFFSET BC7
file1 = 3F
file2 = 9D
10 mismatches - ending compare

from this code... (minus try/catch and whatnot)

        URL site = new URL(jTextField1.getText());
        URLConnection sock = site.openConnection();
        FileWriter fd = new FileWriter(jTextField2.getText());
        BufferedReader in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
        for (int i = 0; i < sock.getContentLength(); i++)
            fd.write(in.read());
        fd.close();
        in.close();

Essentially I figured since in.read() and fd.write() return and accept an int argument that this would be more than enough space for a byte field and therefore wouldn't drop any data.  Any ideas?
-Graham
0
halodev
Asked:
halodev
  • 2
1 Solution
 
CEHJCommented:
You can't use Reader/Writer for binary files. Use BufferedInputStream and BufferedOutputStream
0
 
CEHJCommented:
:-)
0

Featured Post

Prep for the ITIL® Foundation Certification Exam

December’s Course of the Month is now available! Enroll to learn ITIL® Foundation best practices for delivering IT services effectively and efficiently.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now