Java IO流基础
2016-06-28 16:14
549 查看
1.字节流(byte stream):为处理字节的输入和输出提供了方便的方法。例如使用字节流读取或书写二进制数据。
2.字符流(character stream):为字符的输入和输出处理提供了方便。
字节流/字符流:Java中,以stream结尾的都为字节流,以reader、writer结尾的为字符流。
注:在最底层,所有的输入/输出都是字节形式的。
字节流/字符流读、写文件代码如下
private String filePath="F:/java测试.txt"; /** * * @Description:用字节流读取文件 * @throws IOException: 返回结果描述 * @return void: 返回值类型 * @throws */ public void readFileByByte() throws IOException{ //读取文件 FileInputStream fis=new FileInputStream(filePath); //估算文件的长度 int size = fis.available(); for (int i=0;i<size;i++) { //读取每个字节的数据 char a=(char) fis.read(); System.out.println(a); } //关闭输入流 fis.close(); } /** * * @Description:字符流读取文件 * @throws IOException: 返回结果描述 * @return void: 返回值类型 * @throws */ public void readFileByCharacter() throws IOException{ //创建字符流文件读取对象 FileReader fr=new FileReader(filePath); //为文件读取对象建立缓冲区 BufferedReader br=new BufferedReader(fr); String str=null; //br.readLine()从文件中读取一行数据,以回车为结束符,如果没有可读数据返回null while((str=br.readLine())!=null){ System.out.println(str); } //关闭流 br.close(); fr.close(); } /** * * @Description:用字节流写文件 * @throws IOException: 返回结果描述 * @return void: 返回值类型 * @throws */ public void writeFileByByte() throws IOException{ //写文件 FileOutputStream fos=new FileOutputStream(filePath); String str="站在java的角度来记忆,文件输出流为FileOutputStream,文件输入流为FileInputStream"; byte[] b=str.getBytes(); fos.write(b);//写入目标文件 fos.close();//关闭输出流 } /** * * @Description:字符流写文件 * @throws IOException: 返回结果描述 * @return void: 返回值类型 * @throws */ public void writeFileByCharacter() throws IOException{ FileWriter fw=new FileWriter(filePath);//创建文件写入对象 String str="站在java的角度来记忆,文件输出流为FileOutputStream,文件输入流为FileInputStream"; fw.write(str); fw.close(); }
相关文章推荐
- java语言的猜数字游戏代码
- leetcode-java-166. Fraction to Recurring Decimal
- Jersey构建Java RestFul Webservice基础学习教程
- spring.xml从外部文件引入数据库配置信息
- Arrays工具类
- Access restriction
- Java NIO DatagramChannel
- Java通过SMS短信平台实现发短信功能
- Java 如何有效地避免OOM:善于利用软引用和弱引用
- [改善Java代码]线程优先级只使用三个等级
- Java实现监控目录下文件变化
- [改善Java代码]不使用stop方法停止线程
- Spring的事务管理
- spring事务管理几种方式
- spring-mvc加载静态资源文件
- POI-HSSF and POI-XSSF - Java API To Access Microsoft Excel Format Files
- QRcode生成二维码java
- 西安尚学堂告诉你java开发为什么不要过分依赖框架
- Spring IoC知识点整理
- 从事java开发行业,如何从优秀变为卓越