JavaSE——IO流-字符流

8 篇文章 0 订阅
7 篇文章 0 订阅

字符流出现的原因

编码和解码

编码: 就是把字符串转换成字节数组

  • public byte[] getBytes();
    使用平台的默认字符集将此 String编码为 byte 序列,并将结果存储到一个新的 byte 数组中。
  • public byte[] getBytes(String charsetName)
    使用指定的字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中。

解码: 把字节数组转换成字符串

  • public String(byte[] bytes):
    通过使用平台的默认字符集解码指定的 byte 数组,构造一个新的 String。
  • public String(byte[] bytes, String charsetName)
    通过使用指定的 charset 解码指定的 byte 数组,构造一个新的 String。

字符流出现的原因:由于字节流操作中文不是特别方便,所以,java就提供了字符流。
字符流 = 字节流 + 编码表

import java.io.UnsupportedEncodingException;

public class Demo1 {
    public static void main(String[] args) throws UnsupportedEncodingException {
        //编码:把看得懂的,变成看不懂的,即把中文字符转成字节
        //解码:把看不懂的,变成看的懂的,即把字节变成中文

        //编码
        byte[] bytes = "八千里路云和月".getBytes();//默认的字符集是GBK的
        //解码
        String s = new String(bytes);
        //使用平台的默认字符集将此 String编码为 byte 序列,并将结果存储到一个新的 byte 数组中。
        System.out.println(s);
        //编解码:码表必须一致
        /*UTF-8(8-bit Unicode Transformation Format)
        是一种针对Unicode的可变长度字符编码,又称万国码
        由Ken Thompson于1992年创建。现在已经标准化为RFC 3629。
        UTF-8用1到6个字节编码Unicode字符。
        用在网页上可以统一页面显示中文简体繁体及其它语言(如英文,日文,韩文)。
       */
        //如果UNICODE字符由2个字节表示,则编码成UTF-8很可能需要3个字节
        byte[] bytes1 = "我真的是个好人".getBytes("utf-8");
        //使用指定的字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中。
        //解码
        String s1 = new String(bytes1, "utf-8");
        System.out.println(s1);
    }
}

转换流OutputStreamWriter的使用

构造方法

  • OutputStreamWriter(OutputStream out):
    根据默认编码(GBK)把字节流的数据转换为字符流
  • OutputStreamWriter(OutputStream out,String charsetName):
    根据指定编码把字节流数据转换为字符流

字符流的5种写数据的方式

  • public void write(int c) 写一个字符
  • public void write(char[] cbuf) 写一个字符数组
  • public void write(char[] cbuf,int off,int len) 写一个字符数组的 一部分
  • public void write(String str) 写一个字符串
  • public void write(String str,int off,int len) 写一个字符串的一部分
import java.io.*;

public class Demo2 {
    public static void main(String[] args) throws IOException {
        //字符流的命名特点:结尾都有 writer Reader
        // OutputStreamWriter
        //是字符流通向字节流的桥梁:可以使用指定的码表把要写入流中的字符编码成字节。
        //它使用的字符集可以由名称指定或者显示给定,否则默认为平台的字符集

        //构造方法
        /*
        * OutputStreamWriter(OutputStream out):根据默认编码(GBK)把字节流的数据转换为字符流
		OutputStreamWriter(OutputStream out,String charsetName):根据指定编码把字节流数据转换为字符流
		*/
        //    输出流所关联的文件,如果不存在,会自动创建
        OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream("z.txt"));
        out.write("你");
        out.write("\r\n");//换行
        out.flush();
        
        out.write("你好");
        out.write("\r\n");
        out.flush();
        
        out.write("你且迷这风浪永远二十赶朝暮", 0, 6);//从第一个字符开始,写入6个字符
        out.write("\r\n");
        out.flush();
        
        out.write(new char[]{'a', '9', 98, 'e'});
        out.write("\r\n");
        out.flush();
        //    字符流,需要将数据从缓冲区刷新过去
        
        out.close();
/*z.txt里面写入的内容:
你
你好
你且迷这风浪
a9be*/

    }
}

转换流InputStreamReader的使用

构造方法

  • InputStreamReader(InputStream is):
    用默认的编码(GBK)读取数据
  • InputStreamReader(InputStream is,String charsetName)
    用指定的编码读取数据

字符流的2种读数据的方式

  • public int read()
    一次读取一个字符
  • public int read(char[] cbuf)
    一次读取一个字符数组 如果没有读到 返回-1
public class Demo3 {
    public static void main(String[] args) throws IOException {
        /*InputStreamReader是字节流通过字符流的桥梁;
         * 它使用指定的charset读取字节并将其解码为字符。
         * 它使用的字符集可以是由名称指定或者显示给定,
         * 默认为平台的字符集*/
        //构造方法
        /*InputStreamReader(InputStream in)
         * 创建一个使用默认字符集的 InputStreamReader。
         * InputStreamReader(InputStream in, Charset cs)
         * 创建使用给定字符集的 InputStreamReader。*/

        //    输入流所关联的文件,如果不存在 就会报错
        InputStreamReader in = new InputStreamReader(new FileInputStream("z.txt"));
        //public int read () 一次读取一个字符
        //读取文件中的数据,返回对应的编码值
        // 如果读取不到就返回-1
        int len = in.read();//一次读取一个字符
        System.out.println(len);
        //public int read ( char[] cbuf)一次读取一个字符数组 如果没有读到 返回 - 1
        int index = 0;
        while((index = in.read())!=-1){
            System.out.println((char)index);
        }
		in.close();
    }
}
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class Demo3_1 {
    public static void main(String[] args) throws IOException {
        InputStreamReader in = new InputStreamReader(new FileInputStream("z.txt"));
        char[] chars = new char[1024];
        //int len = in.read(chars);

        //for (char aChar : chars) {
        //    System.out.println(aChar);
        //}

        //System.out.println(new String(chars));

        int len1 = in.read(chars,0,100);
        System.out.println(len1);//21
        String s = new String(chars, 0, len1);
        System.out.println(s);

        in.close();

    }
}

字符流复制文本文件

import java.io.*;

public class Demo4 {
    public static void main(String[] args) throws IOException {
        //字符流读取文本文件
        //字符流只能复制文本文件,文本文件就是可以用Windows自带的笔记本打开的文件。
        //我们现在来赋值Demo1
        InputStreamReader in = new InputStreamReader(new FileInputStream("E:\\Demo1.java"));
        OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream("D:\\Demo_compile.java"));
        char[] chars = new char[100];
        int len = 0;
        while ((len = in.read(chars))!=-1){
            out.write(chars);
            out.flush();
        }
        in.close();
        out.close();
    }
}

FileWriter和FileReader

字符流便捷类: 因为转换流的名字太长了,并且在一般情况下我们不需要制定字符集, 于是java就给我们提供转换流对应的便捷类:

转换流------- ------- ------- ------- 便捷类
OutputStreamWriter ----------------- FileWriter
InputStreamReader ------------------ FileReade

构造方法:

  • FileReader (String filePath)
    filePath是一个文件的完整路径
  • FileReader(File fileObj)
    fileObj 是描述该文件的File对象
  • FileWriter (String filePath)
    filePath 是一个文件的完整路径
  • FileWriter(String filePath, boolean append)
    如果append为true ,输出是附加到文件尾的。
  • FileWriter(File fileObj)
    是描述该文件的File对象

FileWriter和FileReader复制文本文件

import java.io.*;

public class Demo5 {
    public static void main(String[] args) throws IOException {
        FileReader fr = new FileReader("z.txt");
        FileWriter fw = new FileWriter("z_1.txt");
        int len = 0;
        while ((len = fr.read()) != -1) {
            fw.write(len);
            fw.flush();
        }
        fr.close();
        fw.close();
    }
}

字符缓冲流的基本使用

BufferedWriter写出数据 高效的字符输出流
BufferedReader读取数据 高效的字符输入流

字符缓冲流复制文本文件

import java.io.*;

public class Demo6 {
    public static void main(String[] args) throws IOException {
		/*
	        高效的字符输出流:
	        BufferedWriter
	        构造方法:	public BufferedWriter(Writer w)
	        高效的字符输入流:
	        BufferedReader
	        构造方法:   public BufferedReader(Reader e)
        */

        //字符缓冲流复制文本文件
        BufferedReader br = new BufferedReader(new FileReader("E:\\JavaSE——Day20\\src\\IO流_字符流\\Demo2.java"));
        BufferedWriter bw = new BufferedWriter(new FileWriter("DEMO2.java"));
        char[] chars = new char[100];
        int len = 0;
        while ((len = br.read(chars)) != -1) {
            bw.write(chars);
            bw.flush();
        }
        br.close();
        bw.close();
    }
}

字符缓冲流的特殊功能

BufferedWriter:

  • public void newLine():
    根据系统来决定换行符 具有系统兼容性的换行符

BufferedReader:

  • public String readLine():
    一次读取一行数据 是以换行符为标记的 读到换行符就换行 没读到数据返回null
    包含该行内容的字符串,不包含任何行终止符,如果已到达流末尾,则返回 null
import java.io.*;

public class Demo7 {
    public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new FileReader("DEMO2.java"));
        BufferedWriter bw = new BufferedWriter(new FileWriter("DEMO2_00.java"));
    //    采用读取一行,写入一行的方式来复制文本文件
        String line = null;
        while((line=br.readLine())!=null){
            bw.write(line);
            bw.newLine();
            bw.flush();
        }
        br.close();
        bw.close();
    }
}

把集合中的数据存储到文本文件

需求:把ArrayList集合中的字符串数据存储到文本文件
分析:
a: 创建一个ArrayList集合
b: 添加元素
c: 创建一个高效的字符输出流对象
d: 遍历集合,获取每一个元素,把这个元素通过高效的输出流写到文本文件中
e: 释放资源
import java.io.*;
import java.util.ArrayList;
public class Demo8 {
    public static void main(String[] args) throws IOException {
        BufferedWriter bw = new BufferedWriter(new FileWriter("name.txt"));
        ArrayList<String> s_names = new ArrayList<>();
        s_names.add("张三");
        s_names.add("李四");
        s_names.add("王五");
        s_names.add("赵六");
        s_names.add("鬼脚七");
        for (String name : s_names) {
            bw.write(name+"\r\n");
            bw.flush();
        }
        bw.close();
    }
}

把文本文件中的数据存储到集合中

需求:从文本文件中读取数据(每一行为一个字符串数据)到集合中,并遍历集合
分析:
a: 创建高效的字符输入流对象
b: 创建一个集合对象
c: 读取数据(一次读取一行)
d: 把读取到的数据添加到集合中
e: 遍历集合
f: 释放资源
import java.io.*;
import java.util.ArrayList;

public class Demo9 {
    public static void main(String[] args) throws IOException {
        BufferedReader bf = new BufferedReader(new FileReader("name.txt"));
        ArrayList<String> names = new ArrayList<>();
        String c = null;
        while ((c = bf.readLine()) != null) {
            names.add(c);
        }
        for (String name : names) {
            System.out.println(name);
        }
        bf.close();
    }
}

随机获取文本文件中的姓名

需求:我有一个文本文件,每一行是一个学生的名字,请写一个程序,每次允许随机获取一个学生名称
分析:
a: 创建一个高效的字符输入流对象
b: 创建集合对象
c: 读取数据,把数据存储到集合中
d: 产生一个随机数,这个随机数的范围是 0 - 集合的长度 . 作为: 集合的随机索引
e: 根据索引获取指定的元素
f: 输出
g: 释放资源
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;

public class Demo10 {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader("name.txt"));
        ArrayList<String> name = new ArrayList<>();
        String c = null;
        while ((c = br.readLine()) != null) {
            name.add(c);
        }
        Random random = new Random();
        int i = random.nextInt(name.size());//指定类型和范围
        System.out.println(name.get(i));
    }
}

复制单级文件夹

需求: 复制D:\course这文件夹到E:\course
分析:
a: 封装D:\course为一个File对象
b: 封装E:\course为一个File对象,然后判断是否存在,如果不存在就是创建一个目录
c: 获取a中的File对应的路径下所有的文件对应的File数组
d: 遍历数组,获取每一个元素,进行复制
e: 释放资源
import java.io.*;

public class Demo11 {
    public static void main(String[] args) throws IOException {
        File file = new File("D:\\course");
        File file1 = new File("E:\\course");
        file1.createNewFile();//判断是否存在,如果不存在就是创建一个目录
        //public File[] listFiles ():获取指定目录下的所有文件或者文件夹的File数组
        File[] files = file.listFiles();
        for (File afile : files) {
            copyFiles(afile,file1);
        }
    }

    private static void copyFiles(File file, File aimFile) throws IOException {
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(aimFile));
        int len = 0;
        byte[] bytes = new byte[1024];
        while ((len = in.read(bytes))!=-1){
            out.write(len);
            out.flush();
        }
        in.close();
        out.close();
    }
}

复制指定目录下指定后缀名的文件并修改名称

需求: 复制D:\demo目录下所有以.java结尾的文件到E:\demo .并且将其后缀名更改文.jad
import java.io.*;

public class Demo12 {
    public static void main(String[] args) throws IOException {
        File fileA = new File("D:\\demo");
        File fileB = new File("E:\\demo");
        fileB.mkdir();
        copyFile2(fileA, fileB);
        //更改名称
        File[] files = fileB.listFiles();
        for (File file : files) {
            String curretnFileName = file.getName();
            curretnFileName=curretnFileName.replace(".java",".jad");
            File destfile = new File(fileB, curretnFileName);
            file.renameTo(destfile);
        }
    }
   
    private static void copyFile2(File fileA, File fileB) throws IOException {
        //获取所有以.java为结尾的文件,返回一个文件对象数组
        File[] files = fileA.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return new File(dir, name).isFile() && name.endsWith(".java");
            }
        });
        //遍历数组,把文件复制到目标目录中
        for (File file : files) {
            String currentFileName = file.getName();
            File fileB_0 = new File(fileB, currentFileName);
            BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(fileB_0));
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = in.read(bytes)) != -1) {
                out.write(len);
                out.flush();
            }
            in.close();
            out.close();
        }
    }
}

键盘录入学生信息按照总分排序并写入文本文件

import java.io.*;
import java.util.Comparator;
import java.util.Scanner;
import java.util.TreeSet;

public class Demo13 {
    public static void main(String[] args) throws IOException {
        //因为要排序,就选择TreeSet来储存学生对象
        TreeSet<Student> students = new TreeSet<>(new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                //    比较总分
                double num = s2.getTotal() - s1.getTotal();
                //    比较姓名
                //如果参数字符串等于此字符串,则返回值 0;
                //如果此字符串小于字符串参数,则返回一个小于 0 的值;
                //如果此字符串大于字符串参数,则返回一个大于 0 的值。
                double num2 = (num == 0) ? s2.getName().compareTo(s1.getName()) : num;
                return (int) num2;
            }
        });

        //    键盘录入学生信息,把学生信息封装成一个学生对象加入到集合中
        for (int x = 0; x < 3; x++) {
            int i = x + 1;
            System.out.println("第" + i + "个学生信息录入开始................................");

            // 创建一个Scanner对象
            Scanner sc = new Scanner(System.in);
            System.out.println("请您输入第" + i + "个学生的姓名: ");
            String name = sc.nextLine();
            System.out.println("请您输入第" + i + "个学生的语文成绩: ");
            double chineseScoreStr = sc.nextDouble();
            System.out.println("请您输入第" + i + "个学生的数学成绩: ");
            double mathScoreStr = sc.nextDouble();
            System.out.println("请您输入第" + i + "个学生的英语成绩: ");
            double englishScoreStr = sc.nextDouble();

            Student student = new Student(name, chineseScoreStr, mathScoreStr, englishScoreStr);

            students.add(student);
        }
        //    创建一个高效的字符流输出对象
        BufferedWriter bw = new BufferedWriter(new FileWriter("studentInfo.config"));
        //\t\t是制表符
        bw.write("姓名\t\t总分\t\t语文成绩\t\t数学成绩\t\t英语成绩");
        bw.newLine();
        bw.flush();
        for (Student s : students) {
            bw.write(s.getName() + "\t\t" + s.getTotal() + "\t\t" + s.getChineseScore() + "\t\t" + s.getMathScore() + "\t\t" + s.getEnglishScore());
            bw.newLine();
            bw.flush();
        }
        bw.close();
        System.out.println("已录完");

    }
}

//首先创建一个学生类
class Student {
    private String name;
    private double chineseScore;
    private double mathScore;
    private double englishScore;

    public double getTotal() {
        return chineseScore + mathScore + englishScore;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getChineseScore() {
        return chineseScore;
    }

    public void setChineseScore(double chineseScore) {
        this.chineseScore = chineseScore;
    }

    public double getMathScore() {
        return mathScore;
    }

    public void setMathScore(double mathScore) {
        this.mathScore = mathScore;
    }

    public double getEnglishScore() {
        return englishScore;
    }

    public void setEnglishScore(double englishScore) {
        this.englishScore = englishScore;
    }


    public Student() {

    }

    public Student(String name,
                   double chineseScore,
                   double mathScore,
                   double englishScore) {
        this.chineseScore = chineseScore;
        this.name = name;
        this.mathScore = mathScore;
        this.englishScore = englishScore;
    }


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值