整理字节流读取和写入、复制
public class LearnStream {
public void readWrite(){InputStream in=null;
try{
//建立文件读取字节流
in=new FileInputStream("E:/ATM.txt");
int data=0;
//将流中的数据读取到字节数组中,返回当前读取的字节数,读取完毕,返回-1
byte[] by=new byte[32];
//读取文件,直到文件读完
while((data=in.read(by))!=-1){
System.out.println("读了"+data);
System.out.println("还剩:"+in.available());
}
}catch(Exception e){
e.printStackTrace();
}finally{
//用来关闭流
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void writeStream(String s){
OutputStream ot=null;
try {
ot=new FileOutputStream("E:/ATM.txt",true);
ot.write(s.getBytes());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
ot.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void copy(){
//创建输入流和输出流
InputStream in=null;
OutputStream out=null;
try {
//获取资源文件
in=new FileInputStream("E:/ATM.txt");
out=new FileOutputStream("E:/ATM1.txt",true);
byte[] by=new byte[32];
int len=0;
while((len=in.read(by))!=-1){
out.write(by, 0, len);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
out.close();
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
本文详细介绍了如何使用Java中的字节流进行文件读取、写入及复制操作。包括使用FileInputStream读取文件内容,利用FileOutputStream进行文件写入,并演示了如何实现文件的完整复制过程。

3416

被折叠的 条评论
为什么被折叠?



