【发布时间】:2017-04-19 09:50:28
【问题描述】:
我需要通过套接字连接下载图像。目前我有一个字节数组,其中包含一个 .jpg 文件以及一些其他不需要的字节(ffd8)。我需要从我的字节数组中删除这些不需要的字节。我尝试在不删除字节的情况下下载文件,然后我得到了格式损坏的图像。所以我想知道如何从我的字节数组中删除不需要的字节。
在我的代码中:
while (!status) {
byte[] buffer = new byte[1024]; // or 4096, or more
int bytesRead = input.read(buffer, 0, buffer.length);
int availableBytes = input.available();
str2 = str2.append(bytesRead);
ImageDataArray = concat(ImageDataArray, buffer);
countPackets = countPackets + buffer.length;
if (input.available() != 0) {
System.out.println("String:" + str1.toString());
} else break;
}
System.out.println("--------------------out of while ------------------");
File file = new File(Environment.getExternalStorageDirectory().getAbsoluteFile(), "/SteelmanPro/1020/images/image" +filename1);
if (!file.exists()) {
file.createNewFile();
}
}
write(ImageDataArray, Environment.getExternalStorageDirectory().getAbsoluteFile() + "/SteelmanPro/1020/images/image" +filename1);
concat() 方法:
public byte[] concat(byte[]...arrays)
{
// Determine the length of the result array
int totalLength = 0;
for (int i = 0; i < arrays.length; i++)
{
totalLength += arrays[i].length;
}
// create the result array
byte[] result = new byte[totalLength];
// copy the source arrays into the result array
int currentIndex = 0;
for (int i = 0; i < arrays.length; i++)
{
System.arraycopy(arrays[i], 0, result, currentIndex, arrays[i].length);
currentIndex += arrays[i].length;
}
return result;
}
写法:
void write(byte[] aInput, String aOutputFileName) {
Log.e("dfd", "Writing binary file...");
try {
OutputStream output = null;
try {
output = new BufferedOutputStream(new FileOutputStream(aOutputFileName));
output.write(aInput);
} finally {
if (output != null)
output.close();
}
} catch (FileNotFoundException ex) {
Log.e("dfd", "File not found.");
} catch (IOException ex) {
Log.e("dfd", "" + ex);
}
}
【问题讨论】:
-
删除了十几个或更多无意义的空行。不要浪费垂直空间,尤其是在网络上。
标签: java android sockets java-io