将文件转换为字节数组

时间:2012-09-03 11:56:57

标签: java android file bytearray

我正在创建一个目录,即文件并将位图图像存储到该文件中,现在如何将其转换为字节数组

File myDir = new File(root + "/saved_images");      
                myDir.mkdirs();
                Random generator = new Random();
                int n = 10000;
                n = generator.nextInt(n);
                String fname = "Image-"+ n +".jpg";
                File file = new File (myDir, fname);

                if (file.exists ()) file.delete (); 
                try {
                    FileOutputStream out = new FileOutputStream(file);

                    bmp.compress(Bitmap.CompressFormat.JPEG, 90, out);

                    out.flush();
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();

                }

4 个答案:

答案 0 :(得分:0)

不完全确定您要做的是什么,但您可以尝试以下方式:

InputStream is = ...
ByteArrayOutputStream buffer = new ByteArrayOutputStream();

int nRead;
byte[] data = new byte[some huge number, power of 2 preferably];

while ((nRead = is.read(data, 0, data.length)) != -1) {
  buffer.write(data, 0, nRead);
}

buffer.flush();

byte[] byteArray = buffer.toByteArray();

答案 1 :(得分:0)

只需使用此选项即可阅读您保存的文件。

// Returns the contents of the file in a byte array.
public static byte[] getBytesFromFile(File file) throws IOException {
    InputStream is = new FileInputStream(file);

    // Get the size of the file
    long length = file.length();

    // You cannot create an array using a long type.
    // It needs to be an int type.
    // Before converting to an int type, check
    // to ensure that file is not larger than Integer.MAX_VALUE.
    if (length > Integer.MAX_VALUE) {
        // File is too large
    }

    // Create the byte array to hold the data
    byte[] bytes = new byte[(int)length];

    // Read in the bytes
    int offset = 0;
    int numRead = 0;
    while (offset = 0) {
        offset += numRead;
    }

    // Ensure all the bytes have been read in
    if (offset 

礼貌:http://www.exampledepot.com

答案 2 :(得分:0)

如果您只想修改现有代码以将图像写入字节数组而不是文件,请使用以下代码替换try块:

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.JPEG, 90, out);
    bytes = out.getBytes();

...其中bytes具有类型byte[],并删除生成文件名的代码并删除现有文件(如果存在)。由于您要写入ByteArrayOutputStream,因此无需在flush()上调用close()out。 (他们不会做任何事情。)

答案 3 :(得分:0)

我已经使用此代码将图像文件转换为字节数组,