Search code examples
javasocketsgedit

Weird stuff while viewing a file which was transferred with sockets in java


Well i am trying to transfer a file using sockets in java

Here is the code

Client Code

try{
    // get streams
    DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
    DataInputStream  din = new DataInputStream (socket.getInputStream());
    dos.writeUTF(fileName);
    dos.flush();

    boolean isOk = din.readBoolean();
    if(!isOk){
        throw new StocFileNotFound("Fisierul: " + fileName +" was not found on:" + address.toString());
    } else {
        baos = new ByteArrayOutputStream();
        byte biti [] = new byte[1024];

        while(din.read(biti,0,1024) != -1){
            baos.write(biti,0,biti.length);
        }
    }

}
catch(IOException e){}
finally {
    try{ socket.close(); } catch (IOException  e){}
}

and then I return the baos.toByteArray() and write it to a file with the OutputStream`s write method.

Server code

try{
    DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
    DataInputStream  din = new DataInputStream (socket.getInputStream());

    // check if it is really a file or if it is an existing file
    File file = new File(din.readUTF());

    // write false
    if ( !file.exists() || !file.isFile() ){
        dos.writeBoolean(false);
        dos.flush();
    }

    // write true and write the file
    else {
        byte biti[] = new byte[1024];
        dos.writeBoolean(true);

        FileInputStream fis = new FileInputStream(file);

        while(fis.read(biti,0,1024) != -1){
            dos.write(biti,0,biti.length);
        }

        dos.flush();

        try{ fis.close(); } catch (IOException e){}

    }

} catch (IOException e){}
finally {
    try{socket.close();}catch(IOException e){}
}

The problem

When i transfer a .txt file and view it in gedit it shows the text followed by multiple \00\00\00, though when i open it using notepad(in wine) it shows only the text. Plus viewing images and .doc works also. So is it something with gedit or is it with my program?

Edit i was sending something like "hi, hope it works!"


Solution

  • This is the problem (or at least a problem):

    while(fis.read(biti,0,1024) != -1)
    {
        dos.write(biti,0,biti.length);
    }
    

    You're always writing out the whole buffer, however many bytes were actually read. You should have:

    int bytesRead;
    while ((bytesRead = fis.read(biti, 0, 1024)) != -1)
    {
        dos.write(biti, 0, bytesRead);
    }
    

    (You've got the same problem in both bits of code.)

    You might want to look at Guava which has various utility methods to relieve you of a lot of the tedium (and possible error) of writing this kind of code over and over again.