30天搞定Java--day26

每日一考和复习

每日一考

  1. 如何遍历Map的key集,value集,key-value集,使用上泛型
Map<Integer, String> map = new HashMap<>();

map.put(1, "aa");
map.put(2, "ab");
map.put(3, "af");
map.put(4, "ag");
map.put(5, "art");
map.put(6, "ah");

Set<Integer> set = map.keySet();
Iterator<Integer> iterSet = set.iterator();
while (iterSet.hasNext()) {
    System.out.println(iterSet.next());
}

Collection<String> listValue = map.values();
Iterator<String> iterValue = listValue.iterator();
while (iterValue.hasNext()) {
    System.out.println(iterValue.next());
}

Set<Map.Entry<Integer, String>> entry = map.entrySet();
for (Map.Entry<Integer, String> e : entry) {
    System.out.println(e.getKey() + "--->" + e.getValue());
}
  1. 写出使用Iterator和增强for循环遍历List的代码,使用上泛型
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");

Iterator<String> iterator = list.iterator();
while (iterator.hasNext()){
    System.out.println(iterator.next());
}

for (String str:list){
    System.out.println(str);
}
  1. 提供一个方法,用于遍历获取HashMap<String,String>中的所有value,并存放在List中返回。考虑上集合中泛型的使用
public List<String> getValueList(Map<String, String> map) {

    Collection<String> values = map.values();

    List<String> list = new ArrayList<>();
    list.addAll(values);
    return list;
}
  1. 创建一个与a.txt文件同目录下的另外一个文件b.txt
File file1 = new File("d:\\test\\a.txt");
File file2 = new File(file1.getParent(),"b.txt");
  1. Map接口中的常用方法有哪些
增:put(K k,V v)
删:V remove(K k)
改:put(K k,V v)
查:get(K k)
长度:size
遍历:keySet  values  entrySet

复习
day25的学习内容

IO流

IO流原理及流的分类

Java IO原理

  • I/O是Input/Output的缩写, I/O技术是非常实用的技术,用于处理设备之间的数据传输。如读/写文件,网络通讯等

  • Java程序中,对于数据的输入/输出操作以“流(stream)” 的方式进行

  • java.io包下提供了各种“流”类和接口,用以获取不同种类的数据,并通过标准的方法输入或输出数据

  • 输入input:读取外部数据(磁盘、光盘等存储设备的数据)到程序(内存)中

  • 输出output:将程序(内存)数据输出到磁盘、光盘等存储设备中

流的分类

  • 按操作数据单位不同分为:字节流(8 bit),字符流(16 bit)
  • 按数据流的流向不同分为:输入流,输出流
  • 按流的角色的不同分为:节点流,处理流

IO流体系
在这里插入图片描述

节点流(文件流)

流程

  1. 实例化File类的对象,指明要操作的文件
  2. 提供具体的流
  3. 数据的读入
  4. 流的关闭操作

这部分类很多,但是步骤就这四步

FileReader fr = null;
try {
    //1.实例化File类的对象,指明要操作的文件
    File file = new File("hello.txt");//相较于当前Module
    //2.提供具体的流
    fr = new FileReader(file);

    //3.数据的读入
    //read():返回读入的一个字符。如果达到文件末尾,返回-1
    //方式一:
    int data = fr.read();
    while (data != -1) {
        System.out.print((char) data);
        data = fr.read();
    }

    //方式二:语法上针对于方式一的修改
    int data;
    while ((data = fr.read()) != -1) {
        System.out.print((char) data);
    }
} catch (IOException e) {
    e.printStackTrace();
} finally {
    //4.流的关闭操作
    try {
        if (fr != null) {
            fr.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    //或
    if (fr != null) {
        try {
            fr.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

对read()操作升级:使用read的重载方法

FileReader fr = null;
try {
    //1.File类的实例化
    File file = new File("hello.txt");

    //2.FileReader流的实例化
    fr = new FileReader(file);

    //3.读入的操作
    //read(char[] cbuf):返回每次读入cbuf数组中的字符的个数。如果达到文件末尾,返回-1
    char[] cbuf = new char[5];
    int len;
    while ((len = fr.read(cbuf)) != -1) {
        //方式一:
        //错误的写法,倒数第二次数组会填满,最后一次对其进行覆盖,数组长度还是5,而真正字符个数只有3
        for (int i = 0; i < cbuf.length; i++) {
            System.out.print(cbuf[i]);
        }
        //正确的写法
        for (int i = 0; i < len; i++) {
            System.out.print(cbuf[i]);
        }
        //方式二:
        //错误的写法,对应着方式一的错误的写法
        String str = new String(cbuf);
        System.out.print(str);
        //正确的写法
        String str = new String(cbuf, 0, len);
        System.out.print(str);
    }
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (fr != null) {
        //4.资源的关闭
        try {
            fr.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  • File对应的硬盘中的文件如果不存在,在输出的过程中,会自动创建此文件
  • File对应的硬盘中的文件如果存在:
    1. 如果流使用的构造器是:FileWriter(file,false) / FileWriter(file):对原有文件的覆盖
    2. 如果流使用的构造器是:FileWriter(file,true):不会对原有文件覆盖,而是在原有文件基础上追加内容
FileReader fr = null;
FileWriter fw = null;
try {
    //1.创建File类的对象,指明读入和写出的文件
    File srcFile = new File("hello.txt");
    File destFile = new File("hello2.txt");

    //不能使用字符流来处理图片等字节数据
    File srcFile = new File("a.jpg");
    File destFile = new File("b.jpg");

    //2.创建输入流和输出流的对象
    fr = new FileReader(srcFile);
    fw = new FileWriter(destFile);

    //3.数据的读入和写出操作
    char[] cbuf = new char[5];
    int len;//记录每次读入到cbuf数组中的字符的个数
    while ((len = fr.read(cbuf)) != -1) {
        //每次写出len个字符
        fw.write(cbuf, 0, len);
    }
} catch (IOException e) {
    e.printStackTrace();
} finally {
    //4.关闭流资源
    //方式一:
    try {
        if (fw != null) {
            fw.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (fr != null) {
                fr.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //方式二:
    try {
        if (fw != null) {
            fw.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        if (fr != null) {
            fr.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

缓冲流

BufferedInputStream
BufferedOutputStream
BufferedReader
BufferedWriter

  • 作用:
    1. 提供流的读取、写入的速度
    2. 提高读写速度的原因:内部提供了一个缓冲区

实现非文本文件的复制

BufferedInputStream bis = null;
BufferedOutputStream bos = null;

try {
    //1.造文件
    File srcFile = new File("a.jpg");
    File destFile = new File("a3.jpg");
    
    //2.造流
    //2.1 造节点流
    FileInputStream fis = new FileInputStream((srcFile));
    FileOutputStream fos = new FileOutputStream(destFile);
    //2.2 造缓冲流
    bis = new BufferedInputStream(fis);
    bos = new BufferedOutputStream(fos);

    //3.复制的细节:读取、写入
    byte[] buffer = new byte[10];
    int len;
    while ((len = bis.read(buffer)) != -1) {
        bos.write(buffer, 0, len);
    }
} catch (IOException e) {
    e.printStackTrace();
} finally {
    //4.资源关闭
    //要求:先关闭外层的流,再关闭内层的流
    //说明:关闭外层流的同时,内层流也会自动的进行关闭。关于内层流的关闭,我们可以省略
    if (bos != null) {
        try {
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    if (bis != null) {
        try {
            bis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

使用BufferedReader和BufferedWriter实现文本文件的复制

BufferedReader br = null;
BufferedWriter bw = null;
try {
    //创建文件和相应的流
    br = new BufferedReader(new FileReader(new File("p.txt")));
    bw = new BufferedWriter(new FileWriter(new File("p1.txt")));

    //读写操作
    //方式一:使用char[]数组
    char[] cbuf = new char[1024];
    int len;
    while ((len = br.read(cbuf)) != -1) {
        bw.write(cbuf, 0, len);
    }

    //方式二:使用String
    String data;
    while ((data = br.readLine()) != null) {
        //方法一:
        bw.write(data + "\n");//data中不包含换行符
        //方法二:
        bw.write(data);//data中不包含换行符
        bw.newLine();//提供换行的操作
    }
} catch (IOException e) {
    e.printStackTrace();
} finally {
    //关闭资源
    if (bw != null) {

        try {
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    if (br != null) {
        try {
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

转换流

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

  • 作用:提供字节流与字符流之间的转换

  • 解码:字节、字节数组 —>字符数组、字符串
    编码:字符数组、字符串 —> 字节、字节数组

  • 字符集
    ASCII:美国标准信息交换码
    用一个字节的7位可以表示
    ISO8859-1:拉丁码表。欧洲码表
    用一个字节的8位表示
    GB2312:中国的中文编码表
    最多两个字节编码所有字符
    GBK:中国的中文编码表升级,融合了更多的中文文字符号
    最多两个字节编码
    Unicode:国际标准码,融合了目前人类使用的所有字符。为每个字符分配唯一的字符码
    所有的文字都用两个字节来表示
    UTF-8:变长的编码方式
    可用1-4个字节来表示一个字符

综合使用InputStreamReader和OutputStreamWriter

InputStreamReader isr = null;
OutputStreamWriter osw = null;
try {
    //1.造文件、造流
    File file1 = new File("dbcp.txt");
    File file2 = new File("dbcp_gbk.txt");

    FileInputStream fis = new FileInputStream(file1);
    FileOutputStream fos = new FileOutputStream(file2);

    isr = new InputStreamReader(fis, "utf-8");
    osw = new OutputStreamWriter(fos, "gbk");

    //2.读写过程
    char[] cbuf = new char[20];
    int len;
    while ((len = isr.read(cbuf)) != -1) {
        osw.write(cbuf, 0, len);
    }
} catch (IOException e) {
    e.printStackTrace();
} finally {

    //3.关闭资源
    if (isr != null) {
        try {
            isr.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    if (osw != null) {
        try {
            osw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

标椎输入、输出(了解)

System.in:标准的输入流,默认从键盘输入
System.out:标准的输出流,默认从控制台输出

  • System类的setIn(InputStream is) / setOut(PrintStream ps)方式重新指定输入和输出的流。

  • 练习:
    从键盘输入字符串,要求将读取到的整行字符串转成大写输出。然后继续进行输入操作,直至当输入“e”或者“exit”时,退出程序

    方法一:使用Scanner实现,调用next()返回一个字符串
    方法二:使用System.in实现。System.in —> 转换流 —> BufferedReader的readLine()流

BufferedReader br = null;
try {
    InputStreamReader isr = new InputStreamReader(System.in);
    br = new BufferedReader(isr);

    while (true) {
        System.out.println("请输入字符串:");
        String data = br.readLine();
        if ("e".equalsIgnoreCase(data) || "exit".equalsIgnoreCase(data)) {
            System.out.println("程序结束");
            break;
        }

        String upperCase = data.toUpperCase();
        System.out.println(upperCase);
    }
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (br != null) {
        try {
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

打印流(了解)

PrintStream
PrintWriter

提供了一系列重载的print() 和 println()

PrintStream ps = null;
try {
    FileOutputStream fos = new FileOutputStream(new File("D:\\IO\\text.txt"));
    // 创建打印输出流,设置为自动刷新模式(写入换行符或字节 '\n' 时都会刷新输出缓冲区)
    ps = new PrintStream(fos, true);
    if (ps != null) {// 把标准输出流(控制台输出)改成文件
        System.setOut(ps);
    }

    for (int i = 0; i <= 255; i++) { // 输出ASCII字符
        System.out.print((char) i);
        if (i % 50 == 0) { 
            System.out.println(); 
        }
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} finally {
    if (ps != null) {
        ps.close();
    }
}

数据流(了解)

DataInputStream
DataOutputStream

作用:用于读取或写出基本数据类型的变量或字符串

练习:将内存中的字符串、基本数据类型的变量写出到文件中

DataOutputStream dos = null;
try {
    dos = new DataOutputStream(new FileOutputStream("data.txt"));

    dos.writeUTF("abc");
    dos.flush();//刷新操作,将内存中的数据写入文件
    dos.writeInt(23);
    dos.flush();
    dos.writeBoolean(true);
    dos.flush();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (dos != null) {
        try {
            dos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

将文件中存储的基本数据类型变量和字符串读取到内存中,保存在变量中
读取不同类型的数据的顺序要与当初写入文件时,保存的数据的顺序一致!

DataInputStream dis = null;
try {
    dis = new DataInputStream(new FileInputStream("data.txt"));

    String name = dis.readUTF();
    int age = dis.readInt();
    boolean isMale = dis.readBoolean();

    System.out.println("name = " + name);
    System.out.println("age = " + age);
    System.out.println("isMale = " + isMale);
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (dis != null) {
        try {
            dis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
发布了42 篇原创文章 · 获赞 68 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_42224119/article/details/105529402
今日推荐