天天看點

重複制造輪子之——位元組數組寫入檔案

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

版權聲明:本文為CSDN部落客「weixin_34008784」的原創文章,遵循CC 4.0 BY-SA版權協定,轉載請附上原文出處連結及本聲明。

原文連結:https://blog.csdn.net/weixin_34008784/article/details/91550672