file transfer with DataInputStream / DataOutputStream

hi there!

I'm implementing a protocol that allows transfer a number of files over a socket TCP.

Files can be .jar, .class or .java . in the first two cases I must send it as binary data,

in the last case, as text .

The protocol is pretty simple,

the sender first sends a String that represent the number of files to send. (ex. "4\n")

then for each file:

1) sends a String that contains the filename and the file size in bytes.

(ex. "Foo.java 1234\n")

2) sends all data readed from file ( binary or text )

My question is how to receive

"Exactly 1234 bytes of text data " from a DataInputStream.

Here is my code:

receiver:

private File getFileAsText(String filename,int bytes, DataInputStream dis )throws IOException{

File incoming =new File(name);

PrintWriter out =new PrintWriter(

new BufferedWriter(

new FileWriter(incoming)));

try{

byte[] inbuf =newbyte[bytes];

readbytes = dis.read(inbuf, 0, inbuf.length);

String content =new String(inbuf, 0, inbuf.length);

out.write(content);

log.info(name +" received ("+ readbytes +" of "+bytes+" bytes)." );

}finally{

if (out !=null){

out.flush();

out.close();

}

}

return incoming;

}

Sender:

privatevoid sendTextFile(DataOutputStream out, File f)throws IOException{

BufferedReader in =new BufferedReader(

new FileReader(f));

try{

System.out.println("--"+ f +"--");

int c;

while( (c = in.read()) != -1 ){

System.out.print((char)c);

out.write(c);

//out.writeChar(c);

}

System.out.println("--END--");

}catch (FileNotFoundException e){

e.printStackTrace();

}

finally{

if (in !=null){

in.close();

}

if (out !=null){

out.flush();

out.close();

}

}

}

[3771 byte] By [fed3xa] at [2007-11-27 8:18:54]
# 1
1. Start a counter at zero.2. Increment it every time you read a byte.3. Stop reading when you've got to the desired value.and 4. Don't use a Reader or a Writer unless you know the data is text. As it isn't, use an InputStream and an OutputStream.
ejpa at 2007-7-12 20:07:12 > top of Java-index,Core,Core APIs...