Java文件与io——字节流

FileOutputStream用于写入诸如图像数据之类的原始字节的流

字节输出流:OutputStream 此抽象类表示输出字节流的所有类的超类。(写)

字节输入流:InputStream(读)

public class ByteStreamDemo {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO 自动生成的方法存根
        write();
        //read();
    }
    
    public static void write(){
        File file=new File("c:\\a.txt");
        try {
            OutputStream out = new FileOutputStream(file,true);//加true每执行一次就会保留一次
            String info="我爱学编程11111111,/.2";
            out.write(info.getBytes());
            out.close();//关闭释放资源
        } catch (FileNotFoundException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
        
    }
    
    public static void read(){
        File file=new File("c:\\a.txt");
        try {
            InputStream in=new FileInputStream(file);
            byte[] bytes=new byte[1024*1024*10];//一次读取10兆
            int len=-1;//Java中规定读到-1就停止
            StringBuffer sb=new StringBuffer();//构造一个其中不带字符的字符串缓冲区,初始容量为 16 个字符。
            while((len=in.read(bytes))!=-1){
                sb.append(new String(bytes, 0, len));
            }
            in.close();
            System.out.println(sb);
        } catch (FileNotFoundException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
    }

}

 

posted on 2016-01-07 12:05  深海溺心  阅读(162)  评论(0编辑  收藏  举报

导航