Sending files from server to client in Java
Posted
by
Lee Jacobson
on Stack Overflow
See other posts from Stack Overflow
or by Lee Jacobson
Published on 2011-02-22T23:03:27Z
Indexed on
2011/02/22
23:25 UTC
Read the original article
Hit count: 260
Hi, 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.
© Stack Overflow or respective owner