Java IO流操作汇总: inputStream 和 outputStream

Java IO流操作汇总: inputStream 和 outputStream我们在进行 Androidjava 开发的时候 经常会遇到各种 IO 流操作 IO 流操作一般分为两类 字符流和字节流 以 Reader 结尾都是字符流 操作的都是字符型的数据 以 Stream 结尾的都是字节流 操作的都是 byte 数据 现将各种常见 IO 流总结如下 一 字节流 1 inputStream 和 outputStream 和 outputStream 为各种输

我们在进行Android java 开发的时候,经常会遇到各种IO流操作。IO流操作一般分为两类:字符流和字节流。以“Reader”结尾都是字符流,操作的都是字符型的数据;以“Stream”结尾的都是字节流,操作的都是byte数据。现将各种常见IO流总结如下:

Java IO流操作汇总: inputStream 和 outputStream

一、字节流

1. InputStream 和 OutputStream

InputStream 和 OutputStream为各种输入输出字节流的基类,所有字节流都继承这两个基类。

2. FileInputStream 和 FileOutputStream

这两个从字面意思很容易理解,是对文件的字节流操作,也会最常见的IO操作流。

 

 /* * 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。 */ public static void readFileByBytes(String inFile, String outFile) { File file = new File(fileName); InputStream in = null; OutputStream out = null; try { byte[] tempbytes = new byte[100]; int byteread = 0; in = new FileInputStream(inFile); out = new FileOutputStream(outFile); while ((byteread = in.read(tempbytes)) != -1) { out.write(tempbytes, 0, byteread); } } catch (Exception e1) { e1.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e1) { } try { out.close(); } catch (IOException e1) { } } } }

 

 

3.DataInputStream和DataOutputStream

 / * DataOutputStream的API测试函数 */ private static void testDataOutputStream() { DataOutputStream out = null; try { File file = new File("file.txt"); out = new DataOutputStream(new FileOutputStream(file)); out.writeBoolean(true); out.writeByte((byte)0x41); out.writeChar((char)0x4243); out.writeShort((short)0x4445); out.writeInt(0x); out.writeLong(0x0FEDCBAL); out.writeUTF("abcdefg"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { out.close(); } catch(IOException e) { } } } / * DataInputStream的API测试函数 */ private static void testDataInputStream() { DataInputStream in = null; try { File file = new File("file.txt"); in = new DataInputStream(new FileInputStream(file)); System.out.printf("byteToHexString(0x8F):0x%s\n", byteToHexString((byte)0x8F)); System.out.printf("charToHexString(0x8FCF):0x%s\n", charToHexString((char)0x8FCF)); System.out.printf("readBoolean():%s\n", in.readBoolean()); System.out.printf("readByte():0x%s\n", byteToHexString(in.readByte())); System.out.printf("readChar():0x%s\n", charToHexString(in.readChar())); System.out.printf("readShort():0x%s\n", shortToHexString(in.readShort())); System.out.printf("readInt():0x%s\n", Integer.toHexString(in.readInt())); System.out.printf("readLong():0x%s\n", Long.toHexString(in.readLong())); System.out.printf("readUTF():%s\n", in.readUTF()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { in.close(); } catch(IOException e) { } } }

4.BufferedInputStream 和 BufferedOutputStream

BufferedInputStream是带缓冲区的输入流,它继承于FilterInputStream。默认缓冲区大小是8M,能够减少访问磁盘的次数,提高文件读取性能。

BufferedOutputStream是带缓冲区的输出流,它继承于FilterOutputStream,能够提高文件的写入效率。

它们提供的“缓冲功能”本质上是通过一个内部缓冲区数组实现的。例如,在新建某输入流对应的BufferedInputStream后,当我们通过read()读取输入流的数据时,BufferedInputStream会将该输入流的数据分批的填入到缓冲区中。每当缓冲区中的数据被读完之后,输入流会再次填充数据缓冲区;如此反复,直到我们读完输入流数据。

 

 public static void readAndWrite(String[] args) { try { BufferedInputStream bis = new BufferedInputStream(new FileInputStream("f:/a.mp3")); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("f:/b.mp3")); byte[] b=new byte[1024]; int len=0; while(-1!= (len = bis.read(b, 0, b.length))) { bos.write(b, 0, len); } } catch (FileNotFoundException e) { System.out.println("文件找不到"); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ if (null! = bos){ bos.close(); } if (null! = bis){ bis.close(); } } }

 

5. ByteArrayInputStream 和 ByteArrayOutputStream

该类从内存中的字节数组中读取数据,它的数据源是一个字节数组,它们分别继承自InputStream 和 OutputStream。

 

 private static byte[] readWithByteArray(byte[] dataSource) { ByteArrayInputStream in = null; ByteArrayOutputStream out = null; try { in = new ByteArrayInputStream(dataSource); out = new ByteArrayOutputStream(); int len = 0; byte[] buffer = new byte[1024]; while ((len = in.read(buffer, 0, buffer.length)) != -1){ out.write(buffer, 0, len); } return out.toByteArray(); } catch (IOException e) { e.printStackTrace(); } finally { try { in.close(); } catch (IOException e1) { } try { out.close(); } catch (IOException e1) { } } }

 

二、字符流

1. InputStreamReader 和 OutputStreamWriter

 InputStreamReader 和 OutputStreamWriter为各种输入输出字符流的基类,所有字符流都继承这两个基类。实际上,这两个类内部各自持有一个inputStream 和 outputStream对象,相当于是对inputStream 和 outputStream进行了包装,将输入字节流转换成字符流,便于读写操作。

 

 / * 以字符为单位读取文件,常用于读文本,数字等类型的文件 */ public static void readFileByChars(String fileName) { File file = new File(fileName); Reader reader = null; try { System.out.println("以字符为单位读取文件内容,一次读一个字节:"); //1. 一次读一个字符 reader = new InputStreamReader(new FileInputStream(file));//可以是任意的InputStream类,不一定必须是FileInputStream int tempchar; while ((tempchar = reader.read()) != -1) { if (((char) tempchar) != '\r') { System.out.print((char) tempchar); } } reader.close(); } catch (Exception e) { e.printStackTrace(); } try { System.out.println("以字符为单位读取文件内容,一次读多个字节:"); //2. 一次读多个字符 char[] tempchars = new char[30]; int charread = 0; reader = new InputStreamReader(new FileInputStream(fileName)); while ((charread = reader.read(tempchars)) != -1) { for (int i = 0; i < charread; i++) { if (tempchars[i] != '\r') { System.out.print(tempchars[i]); } } } } catch (Exception e1) { e1.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e1) { } } } } 

2. FileReader 和 FileWriter

FileReader 和 FileWriter分别继承自 inputStreamReader 和 outputStreamWriter。它是对读取文件操作系统的封装,所有的读写都是直接操作文件系统。因此如果是频繁读写操作,不建议使用FileReader 和 FileWriter,性能将会非常低,这时你需要使用BufferedReader。

 

 public static void readAndWrite() { FileReader fr = null; FileWriter fw = null; try { fr = new FileReader("C:\\my.txt"); fw = new FileWriter("D:\\you.txt"); //1.读一个字符,写一个字符方法 int ch = 0; while ((ch = fr.read()) != -1) { fw.write(ch); } //2.读一个数组大小,写一个数组大小方法。 char []buf = new char[1024]; int len = 0; while((len = fr.read(buf)) != -1){ fw.write(buf, 0, len); } //3.直接写一个字符串 fw.write("hello world!"); } catch (Exception e) { System.out.println(e.toString()); } finally { if (fr != null) try { fr.close(); } catch (Exception e2) { throw new RuntimeException("关闭失败!"); } if (fw != null){ try { fw.close(); } catch (IOException e) { throw new RuntimeException("关闭失败!"); } } } }

3. BufferedReader 和 BufferedWriter

 

 / * 以行为单位读取文件,常用于读面向行的格式化文件 */ public static void readWithBufferedReader(String fileName) { File file = new File(fileName); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); String tempString = null; int line = 1; // 一次读入一行,直到读入null为文件结束 while ((tempString = reader.readLine()) != null) { System.out.println("line " + line + ": " + tempString); line++; } reader.close(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e1) { } } } }

System.in是一个位流,为了转换为字符流,可使用InputStreamReader为其进行字符转换,然后再使用BufferedReader为其增加缓冲功能。例如:

 public static void readAndWrite() { try { //缓冲System.in输入流 //System.in是位流,可以通过InputStreamReader将其转换为字符流 BufferedReader bufReader = new BufferedReader(new InputStreamReader(System.in)); //缓冲FileWriter BufferedWriter bufWriter = new BufferedWriter(new FileWriter("/sdcard/log/test.txt")); String input = null; //每读一行进行一次写入动作 while(!(input = bufReader.readLine())) { bufWriter.write(input); //newLine()方法写入与操作系统相依的换行字符,依执行环境当时的OS来决定该输出那种换行字符 bufWriter.newLine(); } bufReader.close(); bufWriter.close(); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("没有指定文件"); } catch(IOException e) { e.printStackTrace(); } }

 

三、 RandomAccessFile 

 

 / * 随机读取文件内容 */ public static void readFileByRandomAccess(String fileName) { RandomAccessFile randomFile = null; try { // 打开一个随机访问文件流,按只读方式 randomFile = new RandomAccessFile(fileName, "rw"); long fileLength = randomFile.length(); // 设置读写文件的起始位置 randomFile.seek(0); // 一次读取多个数据 byte[] bytes = new byte[10]; int byteread = 0; while ((byteread = randomFile.read(bytes)) != -1) { System.out.write(bytes, 0, byteread); } //一次写入多个数据 randomFile.write(bytes); // 一次读取单个数据 randomFile() // 一次写入单个数据 randomFile.writeDouble(47.0001); } catch (IOException e) { e.printStackTrace(); } finally { if (randomFile != null) { try { randomFile.close(); } catch (IOException e1) { } } } }

 

 

 

 

 

 

 
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/211054.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月18日 下午11:18
下一篇 2026年3月18日 下午11:18


相关推荐

  • sudoers修改_sudoers配置使用

    sudoers修改_sudoers配置使用sudo是linux下常用的允许普通用户使用超级用户权限的工具,允许系统管理员让普通用户执行一些或者全部的root命令,如halt,reboot,su等等。这样不仅减少了root用户的登陆和管理时间,同样也提高了安全性。Sudo不是对shell的一个代替,它是面向每个命令的。它的特性主要有这样几点:§sudo能够限制用户只在某台主机上运行某些命令。§sudo提供了丰富的日志,详细地记录了每个…

    2022年6月20日
    29
  • pandas数据清洗详细教程_excel数据清洗工具

    pandas数据清洗详细教程_excel数据清洗工具Pandas数据清洗常见方法01读取数据df=pd.read_csv(‘文件名称’)02查看数据特征df.info()03查看数据量df.shape04查看各数字类型的统计量df.describe()05去除重复值df.drop_duplicates(inplace=True)06重置索引data.reset_index(inplace=True,drop=True)07查看缺失值信息data.loc[data[‘列名’].isnull()]01

    2025年9月27日
    4
  • k8sV1.18.0版本一键部署脚本(全部代码在下方)

    k8sV1.18.0版本一键部署脚本(全部代码在下方)

    2021年5月30日
    125
  • IDEA控制台乱码(已解决)

    IDEA控制台乱码(已解决)先来说说我遇到的问题 用 IDEA 打开项目首先可以保证编辑器内不会乱码 启动 Tomcat 后控制台出现乱码 我在网上找了很多方式都没有解决 大多数的方式由以下几种 进入 File gt Settings gt Editor gt FileEncoding 将右侧的所有字符编码改为 UTF 8 进入到 IDEA 安装的 bin 目录下 在 idea exe vmoptions 和 idea64 exe vmoptions 文件内添加 Dfile encoding UTF 8IDEA 内点击 RUN amp g

    2026年3月18日
    2
  • Hadoop入门(八)——本地运行模式+完全分布模式案例详解,实现WordCount和集群分发脚本xsync快速配置环境变量 (图文详解步骤2021)[通俗易懂]

    Hadoop入门(八)——本地运行模式+完全分布模式案例详解,实现WordCount和集群分发脚本xsync快速配置环境变量 (图文详解步骤2021)[通俗易懂]Hadoop运行模式1)Hadoop官方网站:http://hadoop.apache.org/2)Hadoop运行模式包括:本地模式、伪分布式模式以及完全分布式模式。本地模式:单机运行,只是用来演示一下官方案例。生产环境不用。伪分布式模式:也是单机运行,但是具备Hadoop集群的所有功能,一台服务器模拟一个分布式的环境。个别缺钱的公司用来测试,生产环境不用。完全分布式模式:多台服务器组成分布式环境。生产环境使用。本地运行模式(官方WordCount案例)1

    2022年6月2日
    44
  • 蓝牙中的sbc_蓝牙sbc格式和aac差别

    蓝牙中的sbc_蓝牙sbc格式和aac差别在之前《小米的试用哲学:小米AirDots青春版和Redmi红米AirDots无线耳机体验》中,我提到了这两款耳机都支持aptXHD。不过在这两款耳机上,也仅仅支持了aptXHD这个技术,也需要配合高通骁龙手机使用,iOS也就别想了……经过实际测试,这两款耳机均不支持aptXHD技术,在此更正,并对造成的误解致歉!这两款耳机支持SBC、AAC两种编码。小米AirDots青春版和Redmi红…

    2025年10月28日
    4

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号