Question

I'm receiving a File from server and in client I want to save this file to a directory. Here is the code that do the job of saving the File

          FileDetails obj1= (FileDetails)object;
          String str= "A "+obj1.fileExtension+" Received From "+obj1.source;
          JOptionPane.showMessageDialog(null,str,"Success", WIDTH, null);
          FileOutputStream saveFile = new FileOutputStream("F:\\Download\\"+obj1.fileExtension);
          ObjectOutputStream save = new ObjectOutputStream(saveFile);
          byte[] buf= convertToByteArray(obj1.file);
          save.write(buf);
          save.close();

The function convertToByteArray is as following

 private byte[] convertToByteArray(File file){       
       try{
       FileInputStream fis = new FileInputStream(file);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];

        for (int readNum; (readNum = fis.read(buf)) != -1;) {
            bos.write(buf, 0, readNum); //no doubt here is 0
            bos.flush();
            System.out.println("read " + readNum + " bytes,");
        }
        byte[] bytes = bos.toByteArray();
    return bytes;
    } catch (IOException ex) {
        ex.printStackTrace();
    }
       return null;
   }

FileDetails is a serializable Object which contains the file that server sends and the file name in fileExtension. The class is as following -

public class FileDetails implements Serializable{
    public File file;
    public String fileExtension;
    public String source;
    public String destination;

}

now problem is I get Junk Data in the saved file in client side. To test whether I'm receiving pure data from server I've printed the content of the file in console and got expected result. But when I open the saved file in the specified directory I get some Chinese scripts What can I do ? Please help me out.

Était-ce utile?

La solution

Part of the problem is, I think, looking at the file in Notepad. If I open the file in another editor, say TextPad using binary mode, I see that the file starts with a serialization header. Using the ObjectOutputStream serializes the binary data of the file as an object. What I think you want to do is remove the ObjectOutputStream line and instead change it to the following:

FileOutputStream saveFile = new FileOutputStream("F:\\Download\\"+obj1.fileExtension);
//ObjectOutputStream save = new ObjectOutputStream(saveFile);
byte[] buf= convertToByteArray(obj1.file);
saveFile.write(buf);
saveFile.close();

That will write out the bytes ONLY of the file.

Autres conseils

Take a look at the following:

http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#move(java.nio.file.Path, java.nio.file.Path, java.nio.file.CopyOption...)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top