Files 是 Guava 中的一个工具类,它主要提供以下功能
Provides utility methods for working with files.
这里我们只关注它的两个方法:
-
byte[] toByteArray(File file)
Reads all bytes from a file into a byte array -
void write(byte[] from,File to)
Overwrites a file with the contents of a byte array.
第一个方法将文件中全部内容读入到一个字节数组。在Android设备上应注意读取的文件大小,太大的文件可能引起OOM
第二方法将字节数组的内容写入到文件中(会覆盖原有内容)
经常使用到这两个方法,所以自己也实现了一份,加入自己的工具库
/**
* 将字节数组写入文件
*
* @param bytes
* @param to
* @return
*/
public static void write(byte[] from, File to) {
if (from == null) {
throw new NullPointerException("bytes is null");
}
if (to == null) {
throw new NullPointerException("file is null");
}
BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(new FileOutputStream(to));
bos.write(from);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
closeQuietly(bos);
}
}
/**
* 小文件(不超过1MB)转成字节数组
*
* @param file
* @return
* @throws IllegalArgumentException
* 待转换的文件超过 1MB
*/
public static byte[] toBytes(File file) {
if (file == null || file.exists() == false) {
return EMPTY_BYTES;
}
final long size = 1 * _1M;
final long fileLen = file.length();
if (fileLen > size) {
throw new IllegalArgumentException("file length exceeds " + size
+ " B");
}
ByteArrayOutputStream baos = new ByteArrayOutputStream((int) fileLen);
int len = -1;
byte[] buf = new byte[4 * 1024];
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
while (-1 != (len = fis.read(buf))) {
baos.write(buf, 0, len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
closeQuietly(fis);
}
return baos.toByteArray();
}
/**
* 关闭流
*
* @param stream
*/
public static void closeQuietly(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
// ignore
}
}
}
测试代码如下
public void testFile() throws Exception {
sdcardMounted();
File testFile = new File(sdcard(), "test.html");
// guava Files.write(byte[], File)
Files.write("我是cm".getBytes(), testFile);
// guava Files.toByteArray(File)
byte[] bytes = Files.toByteArray(testFile);
assertEquals("我是cm", new String(bytes));
// 自己的实现 IOUtils.toBytes(File)
bytes = IOUtils.toBytes(testFile);
assertEquals("我是cm", new String(bytes));
}
public void testFile2() throws Exception {
sdcardMounted();
File testFile = new File(sdcard(), "test2.html");
// 自己的实现 IOUtils.write(byte[], File)
IOUtils.write("我是cm".getBytes(), testFile);
byte[] bytes = Files.toByteArray(testFile);
assertEquals("我是cm", new String(bytes));
}