我在用JAVA编写一个基本的JAVA服务器时遇到了一些问题。它目前在传送html或css文件方面做得很好。但当涉及到图像时,事情就会变得一团糟。我假设我在读取图像文件并准备发送它们时做了一些错误的事情。但请看一下代码:
public void launch()
{
while(true)
{
try
{
Socket connection = this.server_socket.accept();
...
PrintWriter print_writer = new PrintWriter(connection.getOutputStream());
String response = this.readFile(this.request_header.get("Resource"));
print_writer.print(response);
print_writer.flush();
connection.close();
}
catch(...)
{
...
}
}
}
private String readFile(String path)
{
try
{
...
FileInputStream file_input_stream = new FileInputStream(path);
int bytes = file_input_stream.available();
byte[] response_body = new byte[bytes];
file_input_stream.read(response_body);
this.response_body = new String(response_body);
file_input_stream.close();
this.setResponseHeader(200, file_ext);
this.response_header = this.response_header + "\r\n\r\n" + this.response_body;
}
catch(...)
{
...
}
return this.response_header;
}所以我的浏览器会收到类似这样的信息:
HTTP/1.0 200 OK
Content-type: image/jpeg
[String that was read in readFile()]但是chrome不能正确显示图像,opera也不能全部显示!我曾经使用BufferedReader读取文件,但我发现有人说BufferedReader不能正确处理二进制数据,所以我尝试使用FileInputStream,但问题仍然存在):
提前感谢您的任何提示和帮助(:
发布于 2011-11-01 00:55:42
您必须在两端都使用流:输入流和输出流。读取器和写入器假定内容是Unicode,并对字节流进行调整。当然,PrintWriter是一位作家。
https://stackoverflow.com/questions/7956849
复制相似问题