@Test
public void test2(){
//1。创建一个File类的对象
//2.创建一个FileInputStream类的对象
FileInputStream fis=null;
try {
File file=new File("hello.txt");
fis = new FileInputStream(file);
//初始化和迭代放在一起了
int asciib;
while((asccib=fis.read())!=-1){
System.out.println((char)asciib);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//4.关闭响应的流
if(fis!=null){
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//上述 一个一个ASCII字节码 读取 效率太低
//读的效率问题,字节数组来搞定!
@Test
public void test3() {
//1。创建一个File类的对象
//2.创建一个FileInputStream类的对象
FileInputStream fis=null;
try {
File file=new File("hello.txt");
fis = new FileInputStream(file);
byte[] b=new byte[5]; //读取的数据写到这个字节数组里
int len; //每次读到byte里的实际字节的长度或者个数,不是ASCII字节码值
//初始化和迭代放在一起了
while((len=fis.read(b))!=-1){// 注意 优先级 加了括号
// for(int i=0;i<len;i++){遍历字节数组,将 数组元素(也就是一个一个字节)打印出来,
//遇到汉字就有问题了,因为一个汉字是两个字节组成
// System.out.print((char)b[i]); ascii字节码 强转 成 字符 输出
// } 下面是另外一种方法
String str=new String(b, 0, len);// 通过String构造器:ascii字节码字节数组 转换成 字符串
System.out.print(str);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//4.关闭响应的流
if(fis!=null){
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
// FileOutputStream输出,写到文件里
@Test
public void test4(){
//1.创建一个File对象,表名要写入的位置
//输出的物理文件呢可以不存在,如果不存在的话,会自动创建,如果存在会将原先的文件覆盖
//2.FileOutputStream对象
FileOutputStream fos=null;
try {
File f=new File("hello2.txt");
fos = new FileOutputStream(f);
//3写入字节数组的操作,write()的传入参数 是 byte数组 ,所以将 String类型的转换 成 字节数组 使用 getBytes()
fos.write(new String("1234567").getBytes());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//4.关流
if(fos!=null){
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}