想要每次从for循环中保存值

时间:2014-11-25 11:04:05

标签: java android for-loop

以下是我的代码。我正在将图像转换为bytearray值。 这里 finalPathNames.size()== 4 所以我想每次都保存byteArray值,如 byteArray1,byteArray2,byteArray3,byteArray4 ,它位于 for loop

Set<String> finalPathNames = sharedpre.getStringSet("prePathNames", null);
InputStream is = null;
for (String temp : finalPathNames) {
  try {
    is = new FileInputStream(temp);
    try {
      byteArray  = streamToBytes(is);
    } finally {
      is.close();
    }
  } catch (Exception e) {

  }
} 

是否有任何优化的方法来查找结果值

1 个答案:

答案 0 :(得分:1)

将字节发送到服务器,当您检索它们或将它们保存在列表中时(如果您需要它们超过1次)

// as mentioned in the comments, user wants specifically 4 arrays
byte[][] byteArrays = byte[4][]; //

Set<String> finalPathNames = sharedpre.getStringSet("prePathNames", null);
InputStream is = null;
int index = 0;
for (String temp : finalPathNames) {
    byteArrays[index] = new byte[0]; // in case of exception clear array. possibly set to null
    try {
        is = new FileInputStream(temp);
        try {
            byte[] byteArray  = streamToBytes(is);
            byteArrays[index] = byteArray;
        } finally {
            is.close();
        }
    } catch (Exception e) { 

    }
    finally {
        index++;
    }
}

然后得到的流可用:

byteArrays[0], byteArrays[1], byteArrays[2], byteArrays[3],