IO流:
io流的分类:
总体来看有四大流:
- 字节输入流
- 字节输出流
- 字符输入流
- 字符输出流
总结流的分类:
- 字节输入流:以内存为基准,来自磁盘文件/网络中的数据以字节的形式读入到内存中去的流 。
- 字节输出流:以内存为基准,把内存中的数据以字节写出到磁盘文件或者网络中去的流。
- 字符输入流:以内存为基准,来自磁盘文件/网络中的数据以字符的形式读入到内存中去的流。
- 字符输出流:以内存为基准,把内存中的数据以字符写出到磁盘文件或者网络介质中去的流。
字节流:
文件字节输入流:
以内存为基准,可以把磁盘文件中的数据以字节的形式读到内存中。
构造器:
常用方法:
public static void main(String[] args) throws IOException {
InputStream is = new FileInputStream("day05-file-io-code\\src\\daoen.txt");
// int r1 = is.read();
// System.out.println(r1); //输出 字节编码
// System.out.println((char) r1); //输出 字节编码对应的内容
// int r2 = is.read();
// System.out.println(r2);
// System.out.println((char) r2);
System.out.println("---------------");
//使用循环改进取值
int temp; //一次去一个值
while ((temp = is.read()) != -1){
System.out.print((char) temp);
}
}
/**
* a8æç±ä¸å½
* è¿æ¯ä¸ä¸ªæµè¯ç±»
*/
InputStream is = new FileInputStream("day05-file-io\\src\\dlei05.txt");
// 2、每次读取多个字节。
// public int read(byte[] buffer) : 每次会读取多个字节到字节数组中去,会返回读取的字节个数,如果没有字节可读返回-1
// byte[] buffer = new byte[3];
// int len1 = is.read(buffer);
// System.out.println("读取的字节个数:" + len1);
// String rs1 = new String(buffer);
// System.out.println("内容:" + rs1);
// int len2 = is.read(buffer);
// System.out.println("读取的字节个数:" + len2);
// // 应该是读取多少就倒出多少。
// String rs2 = new String(buffer, 0 , len2);
// System.out.println("内容:" + rs2);
// int len3 = is.read(buffer);
// System.out.println("读取的字节个数:" + len3);
// 3、使用循环改进。
byte[] buffer = new byte[3];
int len; // 记录每次读取的字节个数。
while ((len = is.read(buffer)) != -1) {
String rs = new String(buffer, 0 , len);
System.out.print(rs);
}
注意事项:
- 使用FileInputStream每次读取一个字节,读取性能较差,并且读取汉字输出会乱码。
一次读完全部字节:
自己定义一个字节数组与被读取的文件大小一样大,然后使用该字节数组,一次读完文件的全部字节。
public static void main(String[] args) throws Exception {
File f1 = new File("day05-file-io-code\\src\\daoen3.txt");
InputStream is = new FileInputStream(f1);
//准备一个字节数组,跟文件里面的内容一样
byte[] buffer = new byte[(int) f1.length()];
int len = is.read(buffer); //一次性取完
System.out.println("取到的字节数:"+len);
System.out.println("文件的字节数:"+f1.length());
//输出内容
System.out.println(new String(buffer));
}