字符流的读取和写入

本文详细介绍了如何使用Java中的字节流进行文件读取、写入及复制操作。包括使用FileInputStream读取文件内容,利用FileOutputStream进行文件写入,并演示了如何实现文件的完整复制过程。

整理字节流读取和写入、复制

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();
}

}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值