0

txt file我已经实现了将在 java 中使用udp套接字传输任何内容的程序。我printwriter用来写作和阅读。但是使用它我无法传输除 txt 以外的任何文件(比如我想传输 pdf)。在这种情况下应该怎么做。我正在使用以下函数进行文件写入。

Output_File_Write = new PrintWriter("dummy.txt");
Output_File_Write.print(new String(p.getData())); 
4

2 回答 2

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.

于 2012-11-28T04:42:01.310 回答
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

于 2012-11-28T04:41:18.223 回答