标题: IO流(上) [打印本页] 作者: mortonnnn 时间: 2015-7-18 00:43 标题: IO流(上) 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();
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];