IO流

1 流的分类:

按照数据流向的不同:输入流 输出流

按照处理数据的单位的不同:字节流 字符流(处理的文本文件)

按照角色的不同:节点流(直接作用于文件)处理流

尚硅谷_宋红康_第10章_IO

package lianxi1;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import org.junit.Test;

public class TestFileInputOutputStream {
    @Test //要读取的文件一定要存在
   public void test1(){
    FileInputStream fis = null;
    try {
            File file1 = new File("d:\\io\\helloworld.txt");
            fis = new FileInputStream(file1);
            int b = fis.read();
            while(b!=-1){
                System.out.print((char)b);
                b = fis.read();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally{
            try {
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    @Test
    // 要读取的文件一定要存在
    public void test2() {
        FileInputStream fis = null;
        try {
            File file1 = new File("d:\\io\\helloworld.txt");
            fis = new FileInputStream(file1);
            byte[] b = new byte[6];
            int len;
//            int len = fis.read(b);
//            while (len != -1) {
//                for(int i=0;i<len;i++){
//                   System.out.print((char)b[i]);
//                }
//                len = fis.read(b);
//            }
            while ((len=fis.read(b))!= -1) {
                for(int i=0;i<len;i++){   //是len,不是b.length
                   System.out.print((char)b[i]);
                }
            
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }
}
posted on 2014-12-10 16:58  追梦的小屁孩  阅读(186)  评论(0)    收藏  举报