我正在尝试在 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;
}
最佳答案
这里很简单:
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" />
关于java - 安卓 : How to read file in bytes?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10039672/