且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Android的:如何读取文件中的字节?

更新时间:2023-02-16 13:31:31

这是一个简单的:

 文件文件=新的文件(路径);
INT大小=(INT)file.length();
字节[]字节=新字节【尺寸】;
尝试 {
    的BufferedInputStream BUF =新的BufferedInputStream(新的FileInputStream(文件));
    buf.read(字节,0,bytes.length);
    buf.close();
}赶上(FileNotFoundException异常E){
    // TODO自动生成的catch块
    e.printStackTrace();
}赶上(IOException异常E){
    // TODO自动生成的catch块
    e.printStackTrace();
}
 

I am trying to get file content in bytes in Android application. I have get the file in SD card now want to get the selected file in bytes. I googled but no such success. Please help

Below is the code to get files with extension. Through this i get files and show in spinner. On file selection I want to get file in bytes.

private List 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;
}

here it's a simple:

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();
}