字符缓冲流&Properties

1.字符缓冲流特有功能

BufferedReader可以一次读取文件中的一行数据
BufferedWriter可以写入一行数据

public class BR_BW {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new FileReader("C:\\Users\\Desktop\\文件\\a.txt"));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("C:\\Users\\Desktop\\文件\\b.txt"));
//        一边读一边写
        String line;
        while ((line=bufferedReader.readLine())!=null){
            bufferedWriter.write(line);
            bufferedWriter.newLine();//换行

            bufferedWriter.flush();//刷新缓冲区
        }
        //释放资源
        bufferedReader.close();
       bufferedWriter.close(); //先刷新再关闭
       // bufferedWriter.flush(); 和 bufferedWriter.close();均没有时将无法写出数据
    }
}

1.1点名器练习
在一个xuehao.txt文件中保存多个学生姓名.一个姓名一行,随机找出一个姓名

/*
1.读取students.txt文件中的每一行数据到ArrayList集合
2.从ArrayList集合中随机挑选一个元素
   1) 在集合长度的范围内生成一个随机数,作为索引
   2) 再通过索引获取元素,就是随机挑选的姓名
*/ 
//1.读取students.txt文件中的每一行数据到ArrayList集合
ArrayList集合
ArrayList<String> list=new ArrayList<>();
BufferedReader br=new BufferedReader(new FileReader("students.txt"));
//一次读取一行
String line;
while((line=br.readLine())!=null){
  list.add(line);
}
br.close();

//2.从ArrayList集合中随机挑选一个元素
Random r=new Random();
int index=r.nextInt(list.size());
String name=list.get(index); 

System.out.println(name);

1.2对文件中的内容排序
对student.txt文件中学生信息按照年龄排序, 学号 姓名 年龄

思路:
  1.读取student.txt文件到集合ArrayList
  2.对ArrayList进行排序
  3.把ArrayList集合中的数据写到student.txt文件中
public class Px {
    public static void main(String[] args) throws IOException {
    //1.读取student.txt文件到集合ArrayList
        ArrayList<Student> students = new ArrayList<>();
        BufferedReader bufferedReader = new BufferedReader(new FileReader("D:\\Users\\IdeaProjects\\javaSEV1.0\\day19-code\\student.txt"));      
        String line;
        while((line=bufferedReader.readLine())!=null) {
            String[] split = line.split(",");
            Student stu= new Student(split[0], split[1], Integer.parseInt(split[2]));
            students.add(stu);

        }
        bufferedReader.close();
        //2.对ArrayList进行排序
        Collections.sort(students, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                //按照年龄升序排列
                int num=o1.getAge()-o2.getAge();
                //如果年龄相同,使用学号排序
                if(num==0){
                    num=o1.getList().compareTo(o2.getList());
                }
                return num;
            }
        });
//3.把ArrayList集合中的数据写到student.txt文件中
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("D:\\Users\\IdeaProjects\\javaSEV1.0\\day19-code\\student.txt"));
        for(Student s:students){
            StringBuffer sb = new StringBuffer();
            String s1 = sb.append(s.getList()).append(",").append(s.getName()).append(",").append(s.getAge()).toString();
            bufferedWriter.write(s1);
            bufferedWriter.newLine();
        }
        bufferedWriter.close();
    }
}

2.Properties集合

Properties是一个双列集合,是Map的实现类,它是Hashtable的子类。

Properties集合一般用来存储字符串的键和值,它具备Map集合的方法。

String setProperty(String key,String value) 添加键和和值到集合,如果键重复新的会覆盖旧的值
返回值:被覆盖的值

String getProperty(String key) 根据键获取值

Set<String> stringPropertyNames() 获取键的集合

void store(Write w,String comments) 把Properties集合中的键和值写入文件

void load(Reader r) 把文件的键和值读取到Properties集合中

Properties一般结合软件的配置文件来使用,如统计软件的使用次数,配置文件cofig.properties如下

count=5
public class PP {
    public static void main(String[] args) throws IOException {
        Properties properties = new Properties();
  // 读取配置文件中的键对应的值
        properties.load(new FileReader("D:\\Users\\IdeaProjects\\javaSEV1.0\\day19-code\\count.properties"));
        String value = properties.getProperty("count");
        
     //  把value转换为整数
        int count = Integer.parseInt(value);
        if(count>0){
            //如果大于0就有使用次数
            System.out.println("欢迎...");
//          把值减1,再回写配置文件
            count--;
         properties.setProperty("count",count+"");
         properties.store(new FileWriter("D:\\Users\\IdeaProjects\\javaSEV1.0\\day19-code\\count.properties"),null);

        }else
        {
            System.out.println("gameover");
        }
       

    }
}

3.IO流异常处理

public class IO {
    public static void main(String[] args) {
        FileReader fr=null;
        FileWriter fw=null;
        try {
            fr=new FileReader(new File("D:\\Users\\陈坦\\IdeaProjects\\javaSEV1.0\\day19-code\\Xuehao.txt"));
            fw= new FileWriter(new File("D:\\Users\\陈坦\\IdeaProjects\\javaSEV1.0\\day19-code\\Xh.txt"));
          //一边读一边写
            char[] chars = new char[1024];
            int leng;
            while((leng=fr.read(chars))!=-1){
                fw.write(chars,0,leng);
                fw.flush();
            }
                             
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
//            释放资源
            if(fw!=null){
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fr!=null){
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }       
    }   
}

4.标准的输入输出流

System.out:标准的输出流 是OutputStream的子类 输出目的是控制台

System.in:标准的输入流 是InputStream的子类 数据源是键盘录入

5.打印流

打印流:是有输出没有输入(只能写不能读)
PrintStream
PrintWriter
创建PrintStream流对象时,可以往文件中输出,也可以往控制台输出
//创建流对象
//数据目的是一个文件路径
PrintStream ps=new PrintStream("day10-code/a.txt"); 
//数据目的是一个File对象
//PrintStream ps=new PrintStream(new File("day10-code/a.txt")); 
//数据目的是一个OutputStream流对象,参数true: 自动刷新只对println有效
//PrintStream ps=new PrintStream(new FileOutputStream("C://a.txt"),true);
//数据目的是一个OutputStream流对象,控制台
//PrintStream ps=new PrintStream(System.out);

//write方法:只能写入字节数据
ps.write("hello".getBytes());
ps.write(97);
ps.write("\n".getBytes());

//print方法:可以写任何类型的数据,会原样打印输出到目的地
ps.print('a');
ps.print(3.14);
ps.print(true);
ps.print("hello");

//释放资源
ps.close();

6.序列化流

序列化流可以用来往文件中写对象和读对象

  • ObjectInputStream 序列化
  • ObjectOutputStream 反序列化
    如果一个对象想要被序列化,那么这个类就必须实现Serialzable接口
//创建流对象
ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("C:\\a.txt"));
//写对象
Student stu = new Student("A001", "刘刘", 38);
oos.writeObject(stu);
//释放资源
oos.close();

//创建流对象
ObjectInputStream ois=new ObjectInputStream(new FileInputStream("C:\\a.txt"));
//读取对象
Object obj = ois.readObject();
System.out.println(obj);
//释放资源
ois.close();

为了序列化和反序列化的序列号一致,可以在被序列化的类中自己写一个序列号

public class Student  implements Serializable{
  //自己写一个序列号,固定写法
 private static final long serialVersionUID = -6849794470754287710L;
  ...其他代码....
}

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值