天天看点

字符流介绍字符流介绍FileReader:文件输入流FileWriter:文件输出流转换流

字符流介绍

字符流是封装更适合操作文本符方法。

Reader:字符输入流

Reader是Java中IO库提供的另一个输入流基类。

Reader和InputStream的区别:

InputStream是一个字节流,是以byte为单位进行读取。

Reader是一个字符流,是以char为单位进行读取。

Reader基类声明为:

public abstract class Reader implements Readable, Closeable
           

核心方法:

int read() throws IOException:读取一个字符,并返回字符表示为int类型,读取结束时返回-1。

int read(char cbuf[]) throws IOException :输入流读取到一个char类型数据数据中,返回值读取有效个数,读取结尾时是-1。

int read(char cbuf[], int off, int len) throws IOException:输入流读取到一个char类型数据中,从偏移量off读取长度为len的数据。

Writer:字符输出流

将字符写入到目的地的过程使用Writer。

Writer抽象基类生命形式如下:

public abstract class Writer implements Appendable, Closeable, Flushable 
           

核心方法:

void write(int c) throws IOException :写入单个字符写入到输出流中。

void write(char cbuf[]) throws IOException :写入字符数组到输出流中。

void write(char cbuf[], int off, int len) throws IOException :从字符数组的指定偏移位置写入len长度的数据到输出流中。

void write(String str) throws IOException:将字符串写入到输出流中。

void write(String str, int off, int len) throws IOException:将字符串写入到输出流中,从偏移量off起输入len个数据。

FileReader:文件输入流

public FileReader(String fileName) throws FileNotFoundException  //打开一个字符串路径的流
public FileReader(File file) throws FileNotFoundException  //打开一个file实例的流
           

当文件不存在时,会抛出FileNotFoundException异常,这个和FileInputStream类似的。

FileWriter:文件输出流

public FileWriter(String fileName) throws IOException  以字符串路径来打开字符输出流
public FileWriter(String fileName, boolean append) throws IOException 以字符串路径来打开字符传输流,可以指定是否是追加形式(true)还是覆盖的形式(false)写入数据
public FileWriter(File file) throws IOException 
public FileWriter(File file, boolean append) throws IOException 
           

当文件不存在时,可以创建文件。

转换流

将字节流和字符流进行相互转换

InputStreamReader:将字节输入流转换为字符输入流OutputStreamWriter:将字节输出流转换为字符输出流

public class OutputStreamWriter extends Writer
 
     public OutputStreamWriter(OutputStream out) {
        super(out);
        try {
        //设定编码的过程
            se = StreamEncoder.forOutputStreamWriter(out, this, (String)null);
        } catch (UnsupportedEncodingException e) {
            throw new Error(e);
        }
    }    
           

通过研究Reader的实现

public class FileReader extends InputStreamReader {
    public FileReader(String fileName) throws FileNotFoundException {
        super(new FileInputStream(fileName));
    }
           

FileReader实现是继承自InputStreamReader转换流,转换流的构造使用到FileInputStream字节输入流,FileReader的实现是将读取到的字节流通过转换流(本质是通过编码器将字节按照对应的编码表:ASCII、GBK、UTF-8)将其解析为我们能够识别的文本内容。

缓冲流

提高IO的读取速度字节缓冲流:BufferInputStream、BufferOutputStream字符缓冲流:BufferReader、BufferWriter

特有方法:BufferWritervoid newLine() throws IOException ;根据当前系统,写入一个换行符BufferReaderString readLine() throws IOException //读取文本中一行内容

例题:打印指定文件中出现频率最高的三个数字。

private static ArrayList<Integer> arraylist=new ArrayList<>();//arraylist用来存储文件中的所有数字
 public static void readText(String path) throws IOException//读取文件中所有数字
 {
  BufferedReader reader=new BufferedReader(new InputStreamReader(new FileInputStream(path)));
  String tmp;
  while((tmp=reader.readLine())!=null) {
   String []split=tmp.trim().split(",");//tirm():字符串方法,功能是去除前后的空格,但保留中间的空格;split(String i):以i分割此字符串
   for(String i:split) {
    arraylist.add(Integer.valueOf(i));
   }
  }
 }
 public  static void answer3() {               //打印出现频率最高的数字
  HashMap<Integer,Integer> hashmap=new HashMap<>();
  for(Integer i:arraylist) {
   if(hashmap.containsKey(i)) {
    hashmap.put(i,hashmap.get(i)+1);
   }else {
    hashmap.put(i,1);
   }
  }
  PriorityQueue<Map.Entry<Integer,Integer>> queue=new PriorityQueue<Map.Entry<Integer,Integer>>(5,new Comparator<Map.Entry<Integer,Integer>>() {
   @Override
   public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
    // TODO Auto-generated method stub
    return o1.getValue()-o2.getValue();
   }
  });
  Iterator<Map.Entry<Integer, Integer>> iterator = hashmap.entrySet().iterator();
  while(iterator.hasNext())
  {
   Map.Entry<Integer,Integer> entry=iterator.next();
   if(queue.size()<=3) {
    queue.add(entry);
   }else {
    Map.Entry<Integer, Integer> entry1 = queue.peek();
    if(entry1.getValue()<entry.getValue()) {
     queue.remove();
     queue.add(entry);
    }
   }
  }
  Map.Entry<Integer, Integer> remove=queue.remove();
  System.out.println("数字:"+remove.getKey()+",次数:"+remove.getValue());
  Map.Entry<Integer, Integer> remove1=queue.remove();
  System.out.println("数字:"+remove1.getKey()+",次数:"+remove1.getValue());
  Map.Entry<Integer, Integer> remove2=queue.remove();
  System.out.println("数字:"+remove2.getKey()+",次数:"+remove2.getValue());
 }