JAVA方法DataOutputStream.writeBytes(String s)传递中文乱码问题

本文介绍了在JAVA中遇到的中文乱码问题及其解决方案。问题出现在使用writeBytes方法时,由于JAVA中的char为16位,直接转换为8位字节会导致中文乱码。文章提供了一种新的方法来避免这一问题。

今天接口测试搞定一个中文乱码问题,赶紧记一下~

问题出在writeBytes(String s)这个方法上。

JAVA中的char是16位的,一个char存储一个中文字符,直接用writeBytes方法转换会变为8位,直接导致高8位丢失。从而导致中文乱码。

解决方法:

现转换为字节组,再write写入流。方法如下:

原方法:

out.writeBytes(json.toString());

新方法:

out.write(json.toString.getBytes());


运行:import java.io.*; import java.net.*; import java.nio.file.Files; import java.util.StringTokenizer; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class WebServer { private static final int PORT = 6789; private static final String WEB_ROOT = System.getProperty("user.dir") + File.separator + "webroot"; private static final ExecutorService threadPool = Executors.newFixedThreadPool(10); public static void main(String[] args) { try (ServerSocket serverSocket = new ServerSocket(PORT)) { System.out.println("服务器已启动,监听端口:" + PORT); System.out.println("Web根目录:" + WEB_ROOT); while (true) { Socket clientSocket = serverSocket.accept(); threadPool.execute(new RequestHandler(clientSocket)); } } catch (IOException e) { System.err.println("服务器错误: " + e.getMessage()); } finally { threadPool.shutdown(); } } static class RequestHandler implements Runnable { private static final String CRLF = "\r\n"; private final Socket clientSocket; RequestHandler(Socket socket) { this.clientSocket = socket; } @Override public void run() { try (BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream())) { // 读取请求行 String requestLine = in.readLine(); System.out.println("收到请求:" + requestLine); if (requestLine == null) return; // 解析请求路径 StringTokenizer tokens = new StringTokenizer(requestLine); tokens.nextToken(); // 跳过方法 String fileName = tokens.nextToken(); fileName = WEB_ROOT + (fileName.equals("/") ? "/index.html" : fileName); // 安全路径检查 if (fileName.contains("..")) { sendErrorResponse(out, 403, "Forbidden"); return; } // 处理文件请求 File file = new File(fileName); if (file.exists() && !file.isDirectory()) { sendFileResponse(out, file); } else { sendErrorResponse(out, 404, "Not Found"); } } catch (IOException e) { System.err.println("处理请求错误: " + e.getMessage()); } finally { try { clientSocket.close(); } catch (IOException e) { System.err.println("关闭连接错误: " + e.getMessage()); } } } private void sendFileResponse(DataOutputStream out, File file) throws IOException { String contentType = Files.probeContentType(file.toPath()); byte[] fileData = Files.readAllBytes(file.toPath()); String responseHeader = "HTTP/1.1 200 OK" + CRLF + "Content-Type: " + contentType + CRLF + "Content-Length: " + fileData.length + CRLF + CRLF; out.writeBytes(responseHeader); out.write(fileData); out.flush(); } private void sendErrorResponse(DataOutputStream out, int statusCode, String statusText) throws IOException { String errorHtml = "<html><body><h1>" + statusCode + " " + statusText + "</h1></body></html>"; String response = "HTTP/1.1 " + statusCode + " " + statusText + CRLF + "Content-Type: text/html" + CRLF + "Content-Length: " + errorHtml.length() + CRLF + CRLF + errorHtml; out.writeBytes(response); out.flush(); } } } 如何显示出我的html文件
最新发布
05-28
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值