A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© mortonnnn 中级黑马   /  2015-7-18 00:43  /  413 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

inputStream常用方法:
int read()
int read(byte[] b)
int read(byte[] b,int off, int len)
void close()

outputStream的常用方法:
void write(int b)
void write(byte[] b)
void write(byte[],int off,int len)
void flush();
void close();

inputStream的之类:
ByteArrayInputStream,FileInputStream,FilterInputStream,PipedInputStream,SequenceInputStream,ObjectInputStream


outputStream的子类:
ByteArrayOutputStream,FileOutputStream....

字节流读取文件:
       
public class Example01{

        public void static main(String[] args){

                int i = 0;
                FileInputStream inputStream = new FileInputStream("test.txt");
                while(true){
                        i = inputStream.read();
                        if(i = -1){
                                break;
                        }

                System.out.println(i);
        }
}


字节流输出文件:

public class Example02{
        public void static main(String[] args){
                FileOutputStream outputStream = new FileOutputStream("example.txt);
                String str = "黑马程序员";
                byte[] bytes = str.getBytes();
       
                for(int i = 0 ; i < bytes.length ; i ++){
                        outputStream.write(bytes[i]);
                }

                outputStream.close();
        }
}

直接用write(byte b)要首先清空原来的文件
要想在源文件后面加,用write(byte b , boolean append)

同时使用FileInputStream和FileOutputStream实现文件的拷贝:

class Example04{

        public void static main(String[] args){
               
                FileInputStream in = new FileInputStream("D:\BaiduYunGuanjian");
                FileOutputStream out = new FileOutputStream(E:\新建文件夹);
                int len ;
                long oldTime  = System.currentTimeMillis();
                while( (len = in.read() ) != -1 ){
                        out.write(len);
                }
                long newTime = System.currentTimeMillis();
                long time  = newTime - oldTime;

                in.close();
                out.close();

        }

}


字节流的缓冲区

复习两个知识点:
int read(byte[] b):从输入流中读取若干字节,把它们保存在参数b指定的字节数组中,返回的整数表示读取数字节
void write(bytes[] b, int off, int len):将指定byte数组中从偏移量off开始的len个字节写入输入流

public class Example05 {

        Public void static main(String[] args){
               
                FileInputStream in  = new FileInputStream("D:\BaiduYunGuanjia");
                FileOutputStream out = new FileOutputStream("D:\新建文件夹")
;
               
                int len ; //这个值是用来记录每次读取的最大字节数的
                byte[] b = new byte[1024];

                while((len = in.read(b)) != -1){

                        out.write(b,0,len);
                }

                in.close();
                out.close();
        }
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马