您的位置:首页 > 编程语言 > Java开发

Java使用字节流读取数据

2016-05-17 14:34 441 查看
输入流

public static void main(String[] args) {

try {
//输入流,用来读取数据
FileInputStream fis=new FileInputStream("text.txt");
byte input[]=new byte[40];//创建字节数组
fis.read(input);//将数据读取到input 中
String str=new String(input,"utf-8");
System.out.println(str);
fis.close();//关闭

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}


输出流

public static void main(String[] args) {
try {
//输出流
FileOutputStream fos=new FileOutputStream("textw.txt");
String str="wq123455";
byte[]out=str.getBytes("utf-8");
fos.write(out);//写入数据

fos.close();//关闭
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
;


通过字节流拷贝文件(gif动画)

public static void main(String[] args) {
try {
FileInputStream fis=new FileInputStream("a.gif");
FileOutputStream fos=new FileOutputStream("a_new.gif");
byte  input[]=new byte[30];//字节数组

while (fis.read(input)!=-1) {//读取到input字节数组中

fos.write(input);//将数组写入到新的文件

}

fis.close();
fos.close();
System.out.println("done");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


带缓冲的字节流读取数据,BufferedOutputStream和BufferedInputStream

public static void main(String[] args) {
try {

FileInputStream fis=new FileInputStream("mps.mp4");
BufferedInputStream bis=new BufferedInputStream(fis,1000000);//缓冲输入流,1000=1kb,缓冲区大小
FileOutputStream fos=new FileOutputStream("mas_new.mp4");
BufferedOutputStream bos=new BufferedOutputStream(fos,1000000);//缓存输出流
//大型文件对应的数组可以大些,小型文件就小些
byte input[]=new byte[100000];
long before=System.currentTimeMillis();
int count = 0;//定义个变量
while (bis.read(input)!=-1) {//读取的数据等于-1代表读完,跳出循环
bos.write(input);
count++;

}
bis.close();//后打开的先关闭
fis.close();//先打开的后关闭
bos.close();
fos.close();
long time=System.currentTimeMillis()-before;//读取耗时的时间
System.out.println("耗时"+time+"mm");
System.out.println("共读取了"+count+"次");

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java