This week's book giveaway is in the OCAJP forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide 1Z0-808 and have Jeanne Boyarsky & Scott Selikoff on-line! See this thread for details.
The code in your example is not going to work properly with JPG files.
There are two kinds of I/O classes in Java: there are streams (InputStream and OutputStream) and readers/writers. Streams are for dealing with binary data. Readers and writers are for dealing with text files. In your example, you're using a BufferedReader and a FileWriter, which are both classes designed to be used for reading and writing text files, to copy a JPG file, which is not a text file. You're also trying to store the binary data in a String, which is not designed for storing arbitrary binary data.
If you want to be able to copy arbitrary files (binary or text), use streams, not readers/writers. If you're using Java 7, then copying a file is very simple:
If you want to be able to load image files so that you can for example display them in a GUI, then Java's ImageIO API is useful for that. Note that it doesn't support all image file formats, just a few basic ones (including JPG and PNG).
Another remark: Never catch exceptions and ignore them, as you're doing in lines 16 and 17 of your code. When an exception occurs, you'll not see anything and you won't know that something went wrong. At least print an error message when you catch an exception. For example:
thanks for your reply, I will noted in catch exceptions, you can tell me how to transfer files (txt, jpg, rar, etc.) using UDP protocol,
My idea at the client read the file conversion to binary data into DatagramPacket and send to the server,
the server receive DatagramPacket and create a new file, but I do not know how to convert a file into binary data and vice versa.
Tung Xuan wrote:but I do not know how to convert a file into binary data and vice versa.
All files contain binary data. You don't need to convert them.
File content only becomes text or a spreadsheet or a pdf file or any other format when they are opened by a program that interprets the binary data in that way.
As long as you use the Stream classes that Jesper refers to to handle your file content you should have no problems.
Tung Xuan wrote:thanks for your reply, I will noted in catch exceptions, you can tell me how to transfer files (txt, jpg, rar, etc.) using UDP protocol,
Why UDP? UDP is particularly unsuited for file transfers. You either have to implement sequencing, error handling, and retransmission yourself (all stuff that TCP gives you), or accept the fact that your file may end up with pieces missing or in the wrong order.