我需要将视频文件转换为字节数组,然后将字节数组发送到服务器,但是当我上传字节数组时,服务器未以正确的格式接收它。我将文件转换如下:-
buffer=new byte[1024];
os=new ByteArrayOutputStream();
FileInputStream fis=new FileInputStream(file);
int read;
while ((read=fis.read(buffer))!=-1){
os.write(buffer,0,read);
}
fis.close();
os.close();
答案 0 :(得分:0)
以下是将文件转换为字节的方法[]
第一
File file = new File(path);
int size = (int) file.length();
byte[] bytes = new byte[size];
BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));
buf.read(bytes, 0, bytes.length);
buf.close();
第二
byte bytes[] = new byte[(int) file.length()];
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
DataInputStream dis = new DataInputStream(bis);
dis.readFully(bytes);
第三
byte bytes[] = FileUtils.readFileToByteArray(photoFile)
唯一的缺点是在build.gradle应用程序中添加此依赖项:
implementation 'commons-io:commons-io:2.5'
答案 1 :(得分:0)
File file = new File("filepath");
//init array with file length
byte[] bytesArray = new byte[(int) file.length()];
FileInputStream fis = new FileInputStream(file);
fis.read(bytesArray); //read file into bytes[]
fis.close();
return bytesArray;
试试看!希望它能工作。