Files 是 Guava 中的一個工具類,它主要提供如下功能html
Provides utility methods for working with files.java
這裏咱們只關注它的兩個方法:git
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.ide
第一個方法將文件中所有內容讀入到一個字節數組。在Android設備上應注意讀取的文件大小,太大的文件可能引發OOM工具
第二方法將字節數組的內容寫入到文件中(會覆蓋原有內容)測試
常用到這兩個方法,因此本身也實現了一份,加入本身的工具庫ui
/** * 將字節數組寫入文件 * * @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 } } }
測試代碼以下google
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)); }