You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Java ProcessBuilder执行Linux CAT命令返回文件内容长度异常

问题原因
  • 二进制文件不能用文本流读取:图片属于二进制文件,你用InputStreamReader把输入流按字符编码解析成字符的过程中,二进制里的非文本字节会被错误转换或直接丢弃,导致数据缺失。
  • readLine()会丢失换行相关字节:readLine()读取时会自动去掉行尾的\n或\r\n,但这些字节是图片文件的组成部分,被丢弃后总字节数自然变少。
正确的实现方式

直接读取原始字节流,跳过字符转换步骤:

ByteArrayOutputStream output = new ByteArrayOutputStream();
Process p = new ProcessBuilder("sh", "-c", "cat image.png").start();
InputStream inputStream = p.getInputStream();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
    output.write(buffer, 0, bytesRead);
}
p.waitFor();
// 此时字节数与原文件一致
byte[] imageBytes = output.toByteArray();
System.out.println(imageBytes.length);
更优的替代方案

其实完全没必要调用系统的cat命令读取本地文件,直接用Java原生API读取效率更高:

import java.nio.file.Files;
import java.nio.file.Paths;

// ...

byte[] imageBytes = Files.readAllBytes(Paths.get("image.png"));
System.out.println(imageBytes.length);

内容的提问来源于stack exchange,提问作者Akkad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 05:40:21