使用Java将文件从服务器发送到客户端 [英] Sending files from server to client in Java

查看:1645
本文介绍了使用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.");
}

然后我将fileData作为字符串发送到客户端。这适用于txt文件,但是当涉及到图像时,我发现虽然它创建的文件很好,但是图像不会打开。

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.

推荐答案

如果您正在读/写二进制数据,您应该使用字节流(InputStream) / OutputStream)而不是字符流,并尝试避免像您在示例中所做的那样在字节和字符之间进行转换。

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.

您可以使用以下类从InputStream复制字节到OutputStream:

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);
        }
    }
}

你也不给如何与客户联系的详细信息。这是一个最小的例子,展示了如何将一些字节流式传输到servlet的客户端。 (您需要在响应中设置一些标头并适当地释放资源)。

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
    }
}

这篇关于使用Java将文件从服务器发送到客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆