Simple Java file transfer program problem
Asked Answered
I

3

6

I am trying to do a simple file transfer from server to client.

It needs to go like this:

Client asks for file.

Server sends the file to client.

Now in the code (down below) (this is the only code I found and it was hard to find) It sends me only a text file "good" (and even that only makes it to one line in the client). If i try to send any other file type (like image or rar file) it gets it corrupted.

So, could some one please help me to find some working code (in Java) that can send and receive all types of files, or explain to me what the problem with this code is.

Server side:

public class FileServer {   
    public static void main(String args[])throws IOException
    { 
        ServerSocket ss=null;
        try
        {  
            ss=new ServerSocket(8081);
        }
        catch(IOException e)
        { 
            System.out.println("couldn't listen");
            System.exit(0);
        }
        Socket cs=null;
        try
        { 
            cs=ss.accept();
            System.out.println("Connection established"+cs);
        }
        catch(Exception e)
        { 
            System.out.println("Accept failed");
            System.exit(1);
        } 
        PrintWriter put=new PrintWriter(cs.getOutputStream(),true);
        BufferedReader st=new BufferedReader(new InputStreamReader(cs.getInputStream()));
        String s=st.readLine();
        System.out.println("The requested file is : "+s);
        File f=new File(s);
        if(f.exists())
        { 
            BufferedReader d=new BufferedReader(new FileReader(s));
            String line;
            while((line=d.readLine())!=null)
            {
                put.write(line);
                put.flush();
            }
            d.close();
            System.out.println("File transfered");
            cs.close();
            ss.close();
        }  
    }  
}

Client Side:

class MyClient {
    public static void main(String srgs[])throws IOException
    {
        Socket s=null;
        BufferedReader get=null;
        PrintWriter put=null;
        try
        { 
            s=new Socket("127.0.0.1",8081);
            get=new BufferedReader(new InputStreamReader(s.getInputStream()));
            put=new PrintWriter(s.getOutputStream(),true);
        }  
        catch(Exception e)
        {
            System.exit(0);
        }
        String u,f;
        System.out.println("Enter the file name to transfer from server:");
        DataInputStream dis=new DataInputStream(System.in);
        f=dis.readLine();
        put.println(f);
        File f1=new File("c:\\output");
        FileOutputStream  fs=new FileOutputStream(f1);
        while((u=get.readLine())!=null)
        { 
            byte jj[]=u.getBytes();
            fs.write(jj);
        }
        fs.close();
        System.out.println("File received");
        s.close();
    }
}

yesssssssssssssssssssssssssssssssssssssssssssssssssss at last...

This is the changes

client side.

class MyClient {public static void main(String srgs[])throws IOException
{
    Socket s=null;
    BufferedReader get=null;
    PrintWriter put=null;
    try
    { 
        s=new Socket("127.0.0.1",8081);
        get=new BufferedReader(new InputStreamReader(s.getInputStream()));
        put=new PrintWriter(s.getOutputStream(),true);        
    }  
    catch(Exception e)
    {
        System.exit(0);
    }
    InputStreamReader get2=new InputStreamReader(s.getInputStream());
    String u,f;
    System.out.println("Enter the file name to transfer from server:");
    DataInputStream dis=new DataInputStream(System.in);
    f=dis.readLine();
    put.println(f);
    File f1=new File("c:\\output");
    FileOutputStream  fs=new FileOutputStream(f1);

    BufferedInputStream d=new BufferedInputStream(s.getInputStream());
    BufferedOutputStream outStream = new BufferedOutputStream(new             FileOutputStream(f1));
    byte buffer[] = new byte[1024];
    int read;
    while((read = d.read(buffer))!=-1)
    {
        outStream.write(buffer, 0, read);
        outStream.flush();
    }

    //while((u=get.readLine())!=null)
    // { 
    //    byte jj[]=u.getBytes();
    //    fs.write(jj);
    //} 
    fs.close();
    System.out.println("File received");
    s.close();
    }
}

Server Side.

public class FileServer {   
    public static void main(String args[])throws IOException
    { 
        ServerSocket ss=null;
        try
        {  
            ss=new ServerSocket(8081);
        }
        catch(IOException e)
        { 
            System.out.println("couldn't listen");
            System.exit(0);
        }
        Socket cs=null;
        try
        { 
            cs=ss.accept();
            System.out.println("Connection established"+cs);
        }
        catch(Exception e)
        { 
            System.out.println("Accept failed");
            System.exit(1);
        } 
        PrintWriter put=new PrintWriter(cs.getOutputStream(),true);
        BufferedReader st=new BufferedReader(new InputStreamReader(cs.getInputStream()));
        String s=st.readLine();
        System.out.println("The requested file is : "+s);
        File f=new File(s);
        if(f.exists())
        { 
            BufferedInputStream d=new BufferedInputStream(new FileInputStream(s));
            BufferedOutputStream outStream = new BufferedOutputStream(cs.getOutputStream());
            byte buffer[] = new byte[1024];
            int read;
            while((read = d.read(buffer))!=-1)
            {
                outStream.write(buffer, 0, read);
                outStream.flush();
            }
            d.close();
            System.out.println("File transfered");
            cs.close();
            ss.close();
        }  
    }  
}

Thanks a lot to all of you...

Iphigeniah answered 23/5, 2011 at 19:26 Comment(2)
"some one plz help me to find some working code(in java) that cna send and recive all file type plz." Please spell words like 'please' correctly, use a spell checker & find your shift key. For the sake of clarity in the code, choose one of the two common ways to bracket & indent code blocks then stick to it. For better answers, ask a question.Threaten
do not forget to mark question as solved ;)Radii
R
4

You shouldn't use reader in this case. Reader are supposed to deal when you read/writer character data (text) not binary. Use some kind of InputStream

http://download.oracle.com/javase/tutorial/i18n/text/stream.html

Update: In you server part after f.exist():

BufferedInputStream d=new BufferedInputStream(new FileInputStream(s));
BufferedOutputStream outStream = new BufferedOutputStream(cs.getOutputStream());
byte buffer[] = new byte[1024];
int read;
while((read = d.read(buffer))!=-1)
{
    outStream.write(buffer, 0, read);
    outStream.flush();
}
d.close();
System.out.println("File transfered");
cs.close();
ss.close();
Radii answered 23/5, 2011 at 19:36 Comment(4)
but i use InputStreamReader. "get=new BufferedReader(new InputStreamReader(s.getInputStream()));"Iphigeniah
@dan, InputStreamReader - is a reader. It's reads bytes and then converts them to characters. So you read characters, not bytes. Try to replace all readLine() by read() of InputStream. On server you'll need to read array of bytes from file, write this array to socket. On client read array of bytes from socket and write to file.Radii
when you say "write this array to socke" what do you mean?? how i send it to the client?Iphigeniah
@dan, see updates of my answer. I haven't test, but think it should work. The same for client.Radii
A
1

Reader/Writer class is for character stream only, Reader doc. You should use BufferedInputStream/BufferedOutputStream or something like that for raw/binary data.

Andee answered 23/5, 2011 at 19:46 Comment(0)
N
0

Yes but InpustStreamReader is still a Reader, which will try to convert the underlying bytes to character data not binary data. Since you're just trying to send the raw bytes of a file, don't using anything with "reader" or "writer" in the name - use InputStream and OutputStream (and their subclasses) instead on both the server and client.

Nematic answered 23/5, 2011 at 19:55 Comment(2)
sorry but i little bit confuse. you say that i need to send binary data, right? now for that i need to conver my file to byte array, but how i actually send it trow the "put.write(line)" in my code, coz my "BufferedReader" (that build from InputStreamReader) has only read that return int or string ...Iphigeniah
You don't need to convert the file to a byte array, you just need to not use any IO class with the word "Reader" or "Writer" in the name. So don't use a PrintWriter or BufferedReader in your server class or client class at all. Replace their usages with appropriate classes that implement InputStream and OutputStream from the Java IO libraryNematic

© 2022 - 2024 — McMap. All rights reserved.