ToB企服应用市场:ToB评测及商务社交产业平台
标题:
IO流详解
[打印本页]
作者:
盛世宏图
时间:
2022-8-25 23:21
标题:
IO流详解
一、IO流概述
1.原理

2.流的分类
3.流的体系,蓝底框为重点掌握的
二、IO流操作
1.节点流-字符流
(1).FileReader读入数据的基本操作
点击查看代码
package com.Tang.io;
import org.junit.Test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class IOTest {
@Test
public void test() {
FileReader fr = null;
//为了保证流资源一定可以执行关闭操作,需要使用try-catch-finally
//读入的文件一定要存在,否则就会报FileNotFoundException。
try {
//将Hello工程下的hello.txt文件内容读入程序中,并输出到控制台
//1.实例化File类对象,指明要操作的文件
File file = new File("hello.txt");
//2.提供具体的流
fr = new FileReader(file);
//3.数据的读入
//read():返回读入的一个字符,如果达到文件末尾,返回-1;否则返回字符的Ascall值
int data = fr.read();
while(data != -1){
System.out.print((char)data);//读取文件第一个字符
data = fr.read();//读取文件下一个字符
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.流的关闭操作
try {
if(fr != null)
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
复制代码
运行结果图
①.FileReader对read()操作升级:使用read的重载方法
代码中for循环处如果写为i < cubf.length会出现一下问题点击查看代码[code]//对read()操作升级:使用read的重载方法 @Test public void test1(){ 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){ //方式一: //错误写法// for (int i = 0; i
欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/)
Powered by Discuz! X3.4