关于其创建 还有注意事项
package IOtest.test1;
import org.junit.Test;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class Tset02 {
@Test
public void test(){
FileReader fr=null; //try中的变量无法被外界使用,需要定义在外边方便执行IO流的关闭
try {
File file = new File("D:\\untitled\\IOtest\\test1\\ss.txt");
fr = new FileReader(file);
int len;
char[] chars = new char[5];
while((len=fr.read(chars))!=-1) //通过返回值是否为-1来判断是否读到了末尾
{
for (int i = 0; i <len ; i++) {
System.out.print(chars[i]);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(fr!=null) //先判断是否找到了文件创建了字符流对象,才能执行流关闭操作
{
try {
fr.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
第二种 (以String储存输出)
局部变化
fr = new FileReader(file);
int len;
char[] chars = new char[5];
while((len=fr.read(chars))!=-1)
{
String s = new String(chars,0,len);//每次从0开始,每次传入len个数据
System.out.print(s);}