java写文件到服务器,使用Java将文件从服务器发送到客户端

本文档解决了一个关于从服务器向客户端发送不同文件类型的问题。作者当前的实现通过将文件读入字符数组并转换为字符串来工作,这适用于文本文件,但不适用于图像文件。问题在于不应将二进制数据转换为字符。建议使用字节流(InputStream/OutputStream)而不是字符流,并提供了IoUtil类的代码示例,用于在输入和输出流之间复制字节。这种方法适用于任何类型的二进制文件传输。
摘要由CSDN通过智能技术生成

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.

解决方案

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

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值