Sending files from server to client in Java
I'm trying to find a way to send files of different file types from a server to a client.
I have this code on the server to put the file into a byte array:
File file = new File(resourceLocation);
byte[] b = new byte[(int) file.length()];
FileInputStream fileInputStream;
try {
fileInputStream = new FileInputStream(file);
try {
fileInputStream.read(b);
} catch (IOException ex) {
System.out.println("Error, Can't read from file");
}
for (int i = 0; i < b.length; i++) {
开发者_开发技巧 fileData += (char)b[i];
}
}
catch (FileNotFoundException e) {
System.out.println("Error, File Not Found.");
}
I then send fileData as a string to the client. This works fine for txt files but when it comes to images I find that although it creates the file fine with the data in, the image won't open.
I'm not sure if I'm even going about this the right way. Thanks for the help.
Don't put it into a string with a char cast. Just have your socket write the byte array you get from the file input stream.
If you're reading/writing binary data you should use byte streams (InputStream/OutputStream) instead of character streams and try to avoid conversions between bytes and chars like you did in your example.
You can use the following class to copy bytes from an InputStream to an OutputStream:
public class IoUtil {
private static final int bufferSize = 8192;
public static void copy(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[bufferSize];
int read;
while ((read = in.read(buffer, 0, bufferSize)) != -1) {
out.write(buffer, 0, read);
}
}
}
You don't give too much details of how you connect with the client. This is a minimal example showing how to stream some bytes to the client of a servlet. (You'll need to set some headers in the response and release the resources appropiately).
public class FileServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Some code before
FileInputStream in = new FileInputStream(resourceLocation);
ServletOutputStream out = response.getOutputStream();
IoUtil.copy(in, out);
// Some code after
}
}
精彩评论