Java 读取 Resource 目录下的可执行文件到新创建的目录后,可执行文件不可用

2022-11-26 15:24:16 +08:00
 noor
1. 新创建一个文件 A
2. 读取 Resource 目录下的可执行文件(c++编译生成的可执行文件)到 A 目录下
3. 复制后的文件大小正确,但可执行文件无法使用。

Resource chipToolResource = new DefaultResourceLoader().getResource("lib/"+name);
File chipTool = new File(System.getProperty("user.dir") + "/lib/"+name);
FileOutputStream chipToolOutputStream =new FileOutputStream(chipTool) ;
byte[] chipToolBytes = new byte[chipToolResource.getInputStream().available()];
chipToolResource.getInputStream().read(chipToolBytes);
chipToolOutputStream.write(chipToolBytes);
chipToolOutputStream.close();

在 windows 下生成的文件 A 里面的可执行文件拷贝到 Linux 上可用。
但在 Linux 下生成的文件 A 里面的可执行文件不可用。
1577 次点击
所在节点    Java
9 条回复
momocraft
2022-11-26 15:27:52 +08:00
大小正确那内容正不正确啊
noor
2022-11-26 15:49:59 +08:00
@momocraft 文件内容不对
wowo243
2022-11-26 15:56:00 +08:00
chmod +x 也不能执行么,md5 对比下呢
noor
2022-11-26 16:07:39 +08:00
@wowo243 不行,比较发现文件里面的内容错乱了。考虑换种写文件方式尝试下。
aguesuka
2022-11-26 17:56:09 +08:00
把 read 改成 readAllBytes
luozic
2022-11-26 18:10:02 +08:00
二进制文件写入不用二进制方式?
luozic
2022-11-26 18:12:02 +08:00
@luozic 说少了 二进制的读写不统一用二进制
xuanbg
2022-11-26 21:34:49 +08:00
chmod 775 filename
noor
2023-03-02 13:59:45 +08:00
过了几个月了突然想起这个问题已经解决了。
问题代码:chipToolResource.getInputStream().available()获取的的字节大小并不一定准确
每个平台实现的实现不一样,windows 上是正确的,linux 上不一定正确。
文档中也有说:
* <p> Note that while some implementations of {@code InputStream} will return
* the total number of bytes in the stream, many will not. It is
* never correct to use the return value of this method to allocate
* a buffer intended to hold all data in this stream.

byte[] chipToolBytes = new byte[chipToolResource.getInputStream().available()];
换了种方式就可以了
File outputFile = new File(tmp+"/chip-cert");
OutputStream outputStream = new FileOutputStream(outputFile);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/898086

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX