Android中的文件io

889 阅读2分钟

一、io中常见的使用方式

image.png

1) 在相映的路径找到文件。new File(file)

2)把文件变成输出流。FileOutPutStream();

3) 通过bufferedoutputstream提高文件的写出速度,缓冲。bufferedoutputstream(需要flush).

4))对数据进行处理。dataoutputstream.

二、装饰模式

image.png

Component:抽象构建接口

ConcreteComponent:具体的构建对象,实现组 件对象接口,通常就是被装饰的原始对象。就 对这个对象添加功能。

Decorator:所有装饰器的抽象父类,需要定义 一个与组件接口一致的接口,内部持有一个 Component对象,就是持有一个被装饰的对象。

ConreteDecoratorA/ConreteDecoratorB:实际 的装饰器对象,实现具体添加功能。

三、io中的装饰器模式

1.字节流(英文)

image.png

1)inputStrem是一个接口。

2)继承inputStream的类实现了read方法,是具体获取数据流的对象。

3)实际的装饰对象是需要传入获取流数据的对象的。它只是对流的处理。

2.字符流(汉字)

image.png

Writer- >FilterWriter->BufferedWriter->OutputStreamWriter->FileWriter->其他

outputStreamWrite可以填写编码模式。

BufferedWriter bufferedWriter = new BufferedWriter(

				new OutputStreamWriter(
						new FileOutputStream(
								new File("src/testtxt/writerAndStream.txt")),"GBK"));

FileWrite 和FileRead把下面的代码封装了一下。

new OutputStreamWriter(new FileOutputStream(new File("src/testtxt/writerAndStream.txt")),"GBK"));

四、File和RandomAccessFile

file

只能按顺序去读。

RandomAccessFile

构造方法:RandomAccessFile raf = newRandomAccessFile(File file, String mode);其中参数 mode 的值可选 "r":可读,"w" :可写,"rw":可读性;

可以从任何一个地方去读。

1)seek方法,不会改变文件长度。读写的时候会从设置的下一个位置开始读写。

2)setLength方法,会改变文件的大小。但是不会修改写入的位置,还是会从头开始写入。

3)使用场景,网络数据的断点续传。

五、Nio的FileChannel

使用方法

fileOutPutStream里就加入了channel.

                FileChannel sourceFileChannel = randomAccessSourceFile.getChannel();
		FileChannel targetFileChannel = randomAccessTargetFile.getChannel();
		
		ByteBuffer byteBuffer = ByteBuffer.allocate(1024*1024);
		try {
			while(sourceFileChannel.read(byteBuffer) != -1) {
				byteBuffer.flip();//设置position到头,limit为读入的最大位置
				targetFileChannel.write(byteBuffer);
				byteBuffer.clear();//position,limit,Capacity都设置成初始位置。
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				sourceFileChannel.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
			
			try {
				targetFileChannel.close();
			}catch (Exception e) {
				e.printStackTrace();
			}
		}