二、java IO--使用字节流读取文件

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
/**
    一、读取文件
    1、建立联系   File对象 源头
    2、选择流     文件输入流  InputStream FileInputStream
    3、操作  : byte[] car =new byte[1024];  +read+读取大小  --->输出
    4、释放资源 :关闭
 */
public class ReadFile {
    public static void main(String[] args) {
        String string = "F:/read.txt";
        myRead(string);
    }
    /**
     * 读取文件
     * @param string
     */
    public static void myRead(String string){
        File file = new File(string);    //1、建立连接
        InputStream is = null;
        try {
            is = new FileInputStream(file);    //2、选择流(此处为输入流)
//            //和上一句功能一样,BufferedInputStream是增强流,加上之后能提高输入效率,建议!
//            is = new BufferedInputStream(new FileInputStream(file));
            int len = 0;
            byte[] car = new byte[1024];
            while((len = is.read(car))!= -1) {    //3、操作:以每次car大小读取
                String ss = new String(car,0,len);    // 将byte类型的数组转化成字符串,方便下面输出
                System.out.println(ss);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println("文件不存在!");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("读取文件失败!");
        }finally {
            if (is != null) {    //若is还存在就需要释放,否则不需要释放
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    System.out.println("关闭文件输入流失败");
                }
            }
        }
    }
}

 

posted @ 2018-01-29 17:14  JQS  阅读(4460)  评论(0编辑  收藏  举报