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();
}
}
}

