首页 > 解决方案 > 如何从数组中的文件路径中获取字节数组?

问题描述

我需要从文件路径中获取字节数组来上传图像。但是数组形式的字节数组。我如何获得字节数组。我已按照以下步骤操作,但找不到解决方案。

我尝试了以下代码,但不起作用。

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) 它以字符串形式返回但我需要数组形式。请帮助我如何做到这一点。

标签: javaandroidarrays

解决方案


将字节转换为文件,请参见下面的代码。

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());

推荐阅读