泛型和IO流
泛型
为什么要有泛型
泛型就是说明数据类型的参数。相当于C++中的模板template。一旦规定了类型,后续设计到泛型的地方就都只能用该类型。
在集合中使用泛型
package com.packtest.java;/*
@author LiRui
@create 2021-11-01 14:26
*/
import org.junit.Test;
import java.util.ArrayList;
public class GenericTest {
//在集合中使用泛型之前的情况
@Test
public void test1(){
ArrayList list = new ArrayList();
list.add(78);
list.add(76);
list.add(89);
list.add(88);
//问题一:类型不安全
//list.add("Tom");
for(Object score:list){
//问题二:强转时,可能出现类型转换异常
int stuScore=(Integer)score;
System.out.println(stuScore);
}
}
//在集合中使用泛型的情况
@Test
public void test2(){
ArrayList<Integer> list = new ArrayList<Integer>();//使用泛型时不能使用基本数据类型,得使用包装类
list.add(78);
list.add(76);
list.add(89);
list.add(88);
//编译时会进行类型检查
//list.add("Tom");
for(Integer score:list){
//避免了强转操作
int stuScore= score;
System.out.println(stuScore);
}
}
}
如果实例化时没有指定泛型的类型,则默认为Object
自定义泛型结构
泛型类、泛型接口、泛型方法
class Order<T>{//T或者E
//类的内部结构可以使用类的泛型
T orderT;
}
泛型在继承上的体现
子类在继承带泛型的父类时,如果指明了泛型类型。则实例化子类对象时,不需要再指明泛型。如果没有指明则需要将泛型保存下来。
泛型方法
在方法中出现了泛型的结构,泛型的参数与类的泛型参数没有任何关系。或者泛型方法所属的类是不是泛型类都没有关系。
通配符的使用
通配符:?
使用方法List<?> list=null;
表示是具体泛型例如 List<Object> List<String>等并列泛型的通用父类
List<Object> list1=null;
List<String> list2=null;
List<?> list=null;
list=list1;
list=list2;
类A是类B的父类,但是G<A>和G<B>没有关系,二者共同父类是G<?>。使用通配符后不能向list里面添加数据。除了添加null之外。
对于泛型指定的类型有条件约束。
IO流
File类的使用
IO流原理以及流的分类
节点流或文件流
读取文件防异常版本
文本文件用FileReader字符流,图片之类的用FileInputStream字节流。
Ctrl+Alt+T 一键补全异常处理try catch
缓冲流
处理流是对节点流的包装,缓冲流是对于字节流和字符流的包装,目的是加快读取速度。
BufferedReader br = null;
BufferedWriter bw = null;
try {
// 创建缓冲流对象:它是处理流,是对节点流的包装
br = new BufferedReader(new FileReader("d:\\IOTest\\source.txt"));
bw = new BufferedWriter(new FileWriter("d:\\IOTest\\dest.txt"));
String str;
while ((str = br.readLine()) != null) { // 一次读取字符文本文件的一行字符
bw.write(str); // 一次写入一行字符串
bw.newLine(); // 写入行分隔符
}
bw.flush(); // 刷新缓冲区
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭IO流对象
try {
if (bw != null) {
bw.close(); // 关闭过滤流时,会自动关闭它所包装的底层节点流
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (br != null) {
br.close();
}
} catch (IOException e) {
e.printStackTrace();
} }
转换流
public void testMyInput() throws Exception {
FileInputStream fis = new FileInputStream("dbcp.txt");
FileOutputStream fos = new FileOutputStream("dbcp5.txt");
InputStreamReader isr = new InputStreamReader(fis, "GBK");
OutputStreamWriter osw = new OutputStreamWriter(fos, "GBK");
BufferedReader br = new BufferedReader(isr);
BufferedWriter bw = new BufferedWriter(osw);
String str = null;
while ((str = br.readLine()) != null) {
bw.write(str);
bw.newLine();
bw.flush();
}
bw.close();
br.close();
}
标准输入、输出流
System.in是字节流,需要用转换流变成其他类型,随后完成读取。
System.out.println("请输入信息(退出输入e或exit):");
// 把"标准"输入流(键盘输入)这个字节流包装成字符流,再包装成缓冲流
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = null;
try {
while ((s = br.readLine()) != null) { // 读取用户输入的一行数据 --> 阻塞程序
if ("e".equalsIgnoreCase(s) || "exit".equalsIgnoreCase(s)) {
System.out.println("安全退出!!");
break; }
// 将读取到的整行字符串转成大写输出
System.out.println("-->:" + s.toUpperCase());
System.out.println("继续输入信息");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close(); // 关闭过滤流时,会自动关闭它包装的底层节点流
}
} catch (IOException e) {
e.printStackTrace();
} }
打印流
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) { // 每50个数据一行
System.out.println(); // 换行
} }
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (ps != null) {
ps.close();
} }
数据流
DataOutputStream dos = null;
try { // 创建连接到指定文件的数据输出流对象
dos = new DataOutputStream(new FileOutputStream("destData.dat"));
dos.writeUTF("我爱北京天安门"); // 写UTF字符串
dos.writeBoolean(false); // 写入布尔值
dos.writeLong(1234567890L); // 写入长整数
System.out.println("写文件成功!");
} catch (IOException e) {
e.printStackTrace();
} finally { // 关闭流对象
try {
if (dos != null) {
// 关闭过滤流时,会自动关闭它包装的底层节点流
dos.close();
}
} catch (IOException e) {
e.printStackTrace();
} }
DataInputStream dis = null;
try {
dis = new DataInputStream(new FileInputStream("destData.dat"));
String info = dis.readUTF();
boolean flag = dis.readBoolean();
long time = dis.readLong();
System.out.println(info);
System.out.println(flag);
System.out.println(time);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (dis != null) {
try {
dis.close();
} catch (IOException e) {
e.printStackTrace();
} } }
对象流
1.给自定义类加入静态变量 serialVersionUID=xxxxxxL;2.实现 Serializable和Externalizable接口之一。3.保证类中的所有属性可以序列化,基本数据类型和String可序列化。如果含有其他类的对象,则其他类都需要序列化。4.不能序列化static和transient修饰的成员变量。
随机存取文件流
又可以作为输入和输出流,直接继承Object。写数据的时候会对已有文件从头进行覆盖。
读取文件内容
RandomAccessFile raf = new RandomAccessFile(“test.txt”, “rw”);
raf.seek(5);
byte [] b = new byte[1024];
int off = 0;
int len = 5;
raf.read(b, off, len);
String str = new String(b, 0, len);
System.out.println(str);
raf.close();
写入文件内容
RandomAccessFile raf = new RandomAccessFile("test.txt", "rw");
raf.seek(5);
//先读出来
String temp = raf.readLine();
raf.seek(5);
raf.write("xyz".getBytes());
raf.write(temp.getBytes());
raf.close();
插入字符
RandomAccessFile raf1 = new RandomAccessFile("hello.txt", "rw");
raf1.seek(5);
//方式一:
//StringBuilder info = new StringBuilder((int) file.length());
//byte[] buffer = new byte[10];
//int len;
//while((len = raf1.read(buffer)) != -1){
info += new String(buffer,0,len);
//info.append(new String(buffer,0,len));
//}
//方式二:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[10];
int len;
while((len = raf1.read(buffer)) != -1){
baos.write(buffer, 0, len);
}
NIO.2中Path,Paths,Files类的使用
NIO是面向缓冲区的、基于通道的IO操作。