用字节流读写文件

来源:互联网 发布:散粉 知乎 编辑:程序博客网 时间:2024/04/29 06:12

一:IO流分类

1)按流向分:输入流和输出流

2)按数据类型:字节流:可以是一切文件,如纯文本、图片、音乐、视频等

  字符流:只能是纯文本文件

3)按功能分:节点:包裹源头

      处理:增强功能,提供性能

二:字节流(重点)、字符流与文件

1).字节流:输入流:InputStream read(byte[] b) read(byte[] b, int off, int len) close()

如果是文件操作实现类就是FileInputStream,其他操作换用其他实现类就是了。

        输出流:OutputStream write(byte[] b) write(byte[] b, int off, int len) close() flush()

如果是文件操作实现类就是FileOutputStream,其他操作换用其他实现类就是了。

2)字符流:输入流:Reader read(char[] cbuf) read(char[] cbuf, int off, int len) close()

如果是文件操作实现类就是FileReader,其他操作换用其他实现类就是了。

    输出流:Writer write(char[] cbuf) write(char[] cbuf, int off, int len) close() flush()

如果是文件操作实现类就是FileWriter,其他操作换用其他实现类就是了。

三:操作流程:

1)建立联系

2)选择流

3)操作

4)释放资源  


四:读取文件内容:

public static void main(String[] args) {// 1.建立联系File src = new File("F:/1.txt");// 2.选择流FileInputStream input = null;// 提升作用域try {// 3.操作input = new FileInputStream(src);byte[] data = new byte[100];// 建立缓冲数组,数组长度可变int len = 0;// 读出的实际长度while ((len = input.read(data)) != -1) {// 不断读取文件内容String info = new String(data, 0, len);// 字节数组转换成字符串System.out.println(info);}} catch (FileNotFoundException e) {e.printStackTrace();System.out.println("文件不存在");} catch (IOException e) {e.printStackTrace();System.out.println("读取文件失败");} finally {// 4.释放资源if (input != null) {try {input.close();} catch (IOException e) {e.printStackTrace();System.out.println("关闭输入流失败");}}}}

五:往文件中写入内容:

public static void main(String[] args) {// 1.建立联系File src = new File("F:/1.txt");// 2.选择流FileOutputStream out = null;// 提升作用域try {out = new FileOutputStream(src, true);// 为true时表示衔接到文件中,为false或者没有时表示覆盖源文件内容// 3.操作String str = "I must study hard\r\n";// \r\n相当于Enter键-->换行符byte[] data = str.getBytes();// 将字符串转换成字节数组out.write(data);out.flush();// 强制冲刷出去} catch (FileNotFoundException e) {e.printStackTrace();System.out.println("文件未找到");} catch (IOException e) {e.printStackTrace();System.out.println("文件写入异常");} finally {if (out != null) {try {out.close();} catch (IOException e) {e.printStackTrace();System.out.println("文件输出流关闭失败");}}}}


0 0
原创粉丝点击