Corrupt file when using Java to download a file

This problem seems to occur inconsistently. We use a java applet to download a file from our website, which we temporarily store on the client machine.

Here is the code we use to save the file:

URL targetUrl = new URL(urlForFile);
InputStream content = (InputStream)targetUrl.getContent();
BufferedInputStream buffered = new BufferedInputStream(content);
File savedFile = File.createTempFile("temp",".dat");

FileOutputStream fos = new FileOutputStream(savedFile);
int letter;
while((letter = buffered.read()) != -1)
    fos.write(letter);
fos.close();

Later I will try to access this file using:

ObjectInputStream keyInStream = new ObjectInputStream(new FileInputStream(savedFile));

In most cases, it works without problems, but each time we get an error:

java.io.StreamCorruptedException: invalid stream header: 0D0A0D0A

which makes me think that it is not saving the file correctly.

+1
source share
5 answers

, , getContent BufferedInputStream, ascii, return return newline (0x0d0a), ObjectInputStream ( .

+4

FTP-, ASCII.

"; type = I" URL.

+1

ObjectInputStream ?

javadoc:

ObjectInputStream ObjectOutputStream.

, , ObjectOutputStream.

FileInputStream.

( )

, .

+1

3 :

  • , , - / !

:

URL targetUrl = new URL(urlForFile);
InputStream is = targetUrl.getInputStream();
File savedFile = File.createTempFile("temp",".dat");
FileOutputStream fos = new FileOutputStream(savedFile);

int count;
byte[] buff = new byte[16 * 1024];
while((count = is.read(buff)) != -1) {
    fos.write(buff, 0, count);
}
fos.close();
content.close();
+1

, . XP, FC ( FC, , ). Unix, , , -.

, , .

, , .

!

0

Source: https://habr.com/ru/post/1702369/


All Articles