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

我试图在 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;
}
116561 次浏览

这里有一个简单的问题:

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

在 Manif.xml 中添加权限:

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

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

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 字节,如果需要,可以为此添加处理。

目前最简单的解决方案是使用 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方法计数

你也可以这样做:

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

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

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

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

一个简单的 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;
}

下面是以块的形式读取整个文件的工作解决方案,以及使用扫描仪类读取大型文件的有效解决方案。

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

如果希望使用上下文中的 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;
}

以字节为单位读取文件,通常用于读取二进制文件,如图片、声音、图像等。 使用下面的方法。

 public static byte[] readFileByBytes(File file) {


byte[] tempBuf = new byte[100];
int byteRead;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();


try {
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
while ((byteRead = bufferedInputStream.read(tempBuf)) != -1) {
byteArrayOutputStream.write(tempBuf, 0, byteRead);
}
bufferedInputStream.close();
return byteArrayOutputStream.toByteArray();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

在 Kotlin,你可以简单地使用:

File(path).readBytes()