java - 如何从数组中的文件路径中获取字节数组?
问题描述
我需要从文件路径中获取字节数组来上传图像。但是数组形式的字节数组。我如何获得字节数组。我已按照以下步骤操作,但找不到解决方案。
我尝试了以下代码,但不起作用。
byte []buffer=new byte[1024];
ByteArrayOutputStream os=new ByteArrayOutputStream();
FileInputStream fis=new FileInputStream(f);
int read;
while ((read=fis.read(buffer))!=-1){
os.write(buffer,0,read);
}
fis.close();
os.close();
它返回字节数组对象,但我需要数组。当我使用 Array.toString(bytearray) 它以字符串形式返回但我需要数组形式。请帮助我如何做到这一点。
解决方案
将字节转换为文件,请参见下面的代码。
InputStream is = Context.openFileInput(someFileName);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
while ((int bytesRead = is.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
byte[] bytes = bos.toByteArray();
或者
byte[] fileContent = Files.readAllBytes(file.toPath());
推荐阅读
- python - KeyError:[列] 不在索引中
- python - 如何映射到熊猫列表列中的值
- javascript - Javascript toFixed(2) 函数不起作用
- python - 在 SELECT 期间创建的列不存在
- delphi - Delphi Rio 10.3.1 Xml数据绑定与重复的段名称
- android - Android - 项目使用 Kotlin,但 Firebase Crashlytics 是 Java
- javascript - YouTube 实时聊天嵌入现在可以在非 www 网站上使用
- c# - 通过单击 ColumnHeader 从左到右移动 DataGridview 的数据
- c# - 圆文本框的角落 c#
- azure - 对 https://login.microsoftonline.com/{{TenantID}}/oauth2/token 进行 HTTP POST 调用时,访问令牌中缺少声明类型角色