Android:如何以字节为单位读取文件?

时间:2012-04-06 05:51:30

标签: java android file

我想在Android应用程序中获取以字节为单位的文件内容。我现在在SD卡中获取文件想要以字节为单位获取所选文件。我用谷歌搜索,但没有这样的成功。请帮忙

以下是获取扩展名文件的代码。通过这个我得到的文件和旋转显示。在文件选择上,我想以字节为单位获取文件。

private List<String> getListOfFiles(String path) {

   File files = new File(path);

   FileFilter filter = new FileFilter() {

      private final List<String> exts = Arrays.asList("jpeg", "jpg", "png", "bmp", "gif","mp3");

      public boolean accept(File pathname) {
         String ext;
         String path = pathname.getPath();
         ext = path.substring(path.lastIndexOf(".") + 1);
         return exts.contains(ext);
      }
   };

   final File [] filesFound = files.listFiles(filter);
   List<String> list = new ArrayList<String>();
   if (filesFound != null && filesFound.length > 0) {
      for (File file : filesFound) {
         list.add(file.getName());
      }
   }
   return list;
}

8 个答案:

答案 0 :(得分:102)

这里很简单:

File file = new File(path);
int size = (int) file.length();
byte[] bytes = new byte[size];
try {
    BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));
    buf.read(bytes, 0, bytes.length);
    buf.close();
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

在manifest.xml中添加权限:

 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

答案 1 :(得分:19)

这是一个解决方案,可以保证读取整个文件,不需要库,并且效率很高:

byte[] fullyReadFileToBytes(File f) throws IOException {
    int size = (int) f.length();
    byte bytes[] = new byte[size];
    byte tmpBuff[] = new byte[size];
    FileInputStream fis= new FileInputStream(f);;
    try {

        int read = fis.read(bytes, 0, size);
        if (read < size) {
            int remain = size - read;
            while (remain > 0) {
                read = fis.read(tmpBuff, 0, remain);
                System.arraycopy(tmpBuff, 0, bytes, size - remain, read);
                remain -= read;
            }
        }
    }  catch (IOException e){
        throw e;
    } finally {
        fis.close();
    }

    return bytes;
}

注意:它假定文件大小小于MAX_INT字节,如果需要,可以为其添加处理。

答案 2 :(得分:17)

今天最简单的解决方案是使用Apache common io:

http://commons.apache.org/proper/commons-io/javadocs/api-release/org/apache/commons/io/FileUtils.html#readFileToByteArray(java.io.File)

byte bytes[] = FileUtils.readFileToByteArray(photoFile)

唯一的缺点是在build.gradle应用中添加此依赖关系:

implementation 'commons-io:commons-io:2.5'

+ 1562方法计数

答案 3 :(得分:11)

由于接受的BufferedInputStream#read不能保证读取所有内容,而不是自己跟踪缓冲区大小,我使用了这种方法:

    byte bytes[] = new byte[(int) file.length()];
    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
    DataInputStream dis = new DataInputStream(bis);
    dis.readFully(bytes);

阻止直到完整读取完成,并且不需要额外的导入。

答案 4 :(得分:0)

你也可以这样做:

byte[] getBytes (File file)
{
    FileInputStream input = null;
    if (file.exists()) try
    {
        input = new FileInputStream (file);
        int len = (int) file.length();
        byte[] data = new byte[len];
        int count, total = 0;
        while ((count = input.read (data, total, len - total)) > 0) total += count;
        return data;
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }
    finally
    {
        if (input != null) try
        {
            input.close();
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }
    return null;
}

答案 5 :(得分:0)

一个简单的InputStream将执行

byte[] fileToBytes(File file){
    byte[] bytes = new byte[0];
    try(FileInputStream inputStream = new FileInputStream(file)) {
        bytes = new byte[inputStream.available()];
        //noinspection ResultOfMethodCallIgnored
        inputStream.read(bytes);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return bytes;
}

答案 6 :(得分:0)

以下是一种有效的解决方案,它可以分块读取整个文件,它是使用扫描程序类读取大文件的有效解决方案。

   try {
        FileInputStream fiStream = new FileInputStream(inputFile_name);
        Scanner sc = null;
        try {
            sc = new Scanner(fiStream);
            while (sc.hasNextLine()) {
                String line = sc.nextLine();
                byte[] buf = line.getBytes();
            }
        } finally {
            if (fiStream != null) {
                fiStream.close();
            }

            if (sc != null) {
                sc.close();
            }
        }
    }catch (Exception e){
        Log.e(TAG, "Exception: " + e.toString());
    }

答案 7 :(得分:0)

如果要为此使用Context中的openFileInput方法,则可以使用以下代码。

这将创建一个BufferArrayOutputStream并将从文件中读取的每个字节附加到该字节。

/**
 * <p>
 *     Creates a InputStream for a file using the specified Context
 *     and returns the Bytes read from the file.
 * </p>
 *
 * @param context The context to use.
 * @param file The file to read from.
 * @return The array of bytes read from the file, or null if no file was found.
 */
public static byte[] read(Context context, String file) throws IOException {
    byte[] ret = null;

    if (context != null) {
        try {
            InputStream inputStream = context.openFileInput(file);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

            int nextByte = inputStream.read();
            while (nextByte != -1) {
                outputStream.write(nextByte);
                nextByte = inputStream.read();
            }

            ret = outputStream.toByteArray();

        } catch (FileNotFoundException ignored) { }
    }

    return ret;
}