FileReader的用法
2015-09-06 08:51
190 查看
package cn.itcast.reader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Arrays; public class Demo1 { public static void main(String[] args) throws IOException { // writeTest(); readrTest(); } //使用字节流读取中文 public static void readrTest() throws IOException{ //找到目标文件 File file = new File("F:\\a.txt"); //建立数据的输入通道 FileInputStream fileInputStream = new FileInputStream(file); //读取内容 //int content = 0; /*while((content = fileInputStream.read())!=-1){ //出现乱码的原因: 一个中文在gbk码表中默认是占两个字节, // 目前你只读取了一个字节而已,所以不是一个完整的中文。 System.out.print((char)content); }*/ byte[] buf = new byte[2]; for(int i = 0 ; i < 3 ; i++){ fileInputStream.read(buf); System.out.print(new String(buf)); } //关闭资源 fileInputStream.close(); } //使用字节流写中文。 字节流之所以能够写中文是因为借助了字符串的getBytes方法对字符串进行了编码(字符---->数字)。 public static void writeTest() throws IOException{ //找到目标文件 File file = new File("F:\\a.txt"); //建立数据的输出通道 FileOutputStream fileOutputStream = new FileOutputStream(file); //准备数据,把数据写出。 String data = "大家好"; byte[] buf = data.getBytes(); //把字符串转换成字节数组 System.out.println("输出的内容:"+ Arrays.toString(buf)); fileOutputStream.write(buf); ///关闭资源 fileOutputStream.close(); } }
package cn.itcast.reader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; /* 字节流:字节流读取的是文件中的二进制数据,读到的数据并不会帮你转换成你看得懂的字符。 字符流: 字符流会把读取到的二进制的数据进行对应 的编码与解码工作。 字符流 = 字节流 + 编码(解码) 输入字符流: ----------| Reader 输入字符流的基类 抽象类 -------------| FileReader 读取文件的输入字符流。 FileReader的用法: 1. 找到目标文件 2. 建立数据的输入通道 3. 读取数据 4. 关闭资源 */ public class Demo2 { public static void main(String[] args) throws IOException { readTest2(); } //使用缓冲字符数组读取文件。 public static void readTest2() throws IOException{ //找到目标文件 File file = new File("F:\\1208project\\day21\\src\\day21\\Demo1.java"); // 建立数据的输入通道 FileReader fileReader = new FileReader(file); //建立缓冲字符数组读取文件数据 char[] buf = new char[1024]; int length = 0 ; while((length = fileReader.read(buf))!=-1){ System.out.print(new String(buf,0,length)); } } public static void readTest1() throws IOException{ //找到目标文件 File file = new File("F:\\1208project\\day21\\src\\day21\\Demo1.java"); //建立数据的输入通道 FileReader fileReader = new FileReader(file); int content = 0 ; while((content = fileReader.read())!=-1){ //每次只会读取一个字符,效率低。 System.out.print((char)content); } //关闭资源 fileReader.close(); } }
相关文章推荐
- 【前端图片处理】图片预览篇
- 黑马程序员_java初操作使用FileReader及FileWriter进行文件复制
- Java 字符流的使用
- 黑马程序员-------IO流(字符流)
- IO流的基础操作FileReader
- 黑马程序员-IO-字符流-FileWriter&FileReader
- java I/O中文件字节输入流 和字符输入流
- 黑马程序员——第18天——IO输入与输出(概述,字符流)
- JAVA学习笔记(三十二)- 字符流 FileReader & FileWriter
- 黑马程序员--IO(1)
- java读取文本文件(每次读一行)
- Java上路16-I/O
- FileWriter,FileReader
- Java 读取xml文件中文乱码问题
- IO包中的其他流对象
- 复制文件
- 用缓冲区实现文件的复制
- FileReader读取文件
- FileReader、FileWrite
- 使用FileReader和FileWriter读取写入文件内容