0

I have implemented the program that will transfer any txt file using the udp socket in java. I am using printwriter to write and read. But using that I am not able to transfer any file other than txt (say i want to transfer pdf). In this case what should be done. I am using the below function for file write.

Output_File_Write = new PrintWriter("dummy.txt");
Output_File_Write.print(new String(p.getData())); 
Hardik Mishra
  • 14,779
  • 9
  • 61
  • 96
user1667630
  • 297
  • 6
  • 15

2 Answers2

4

Writers / PrintWriters are for writing text files. They take (Unicode-based) character data and encode it using the default character encoding (or a specified one), and write that to the file.

A PDF document (as you get it from the network) is in a binary format, so you need to use a FileOutputStream to write the file.


It is also a little bit concerning that you are attempting to transfer documents using UDP. UDP provides no guarantees that the datagrams sent will all arrive, or that they will arrive in the same order as they were sent. Unless you can always fit the entire document into a single datagram, you will have to do a significant amount of work to detect that datagrams have been dropped or have arrived in the wrong order ... and take remedial action.

Using TCP would be far simpler.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • Stephen's right. Implementing UDP-based file transfer is no joke; you would need to write an entire reliability layer on top of it to make it work. For simple transfer of occasional small files, TCP is the only way to go. – Greg Pettit Nov 28 '12 at 06:45
0

AFAIK PrintWriter is meant to be used with Text. Quote from doc

Prints formatted representations of objects to a text-output stream. This class implements all of the print methods found in PrintStream. It does not contain methods for writing raw bytes, for which a program should use unencoded byte streams.

To be able to send binary data you would need to use apt API for it, for example PrintStream

ch4nd4n
  • 4,110
  • 2
  • 21
  • 43