文件流的相关操作

文件的文本内容和图片文件在流中都是以字节的形式;

public class Copy {

public static void main(String[] args) throws IOException {
String from = "D:/filetest/background.jpg";
String to = "D:/filetest/to.jpg";

new Copy().copyText(from,to); //字节流

String source = "D:/filetest/source.txt";
String target = "D:/filetest/target.txt";

new Copy().copusuper(source,target); //字符流

}
/**
* 复制文件from里的内容到文件to里面
* @param from:源文件
* @param to:目标文件
* @throws IOException 
*/
public void copyText(String from, String to) throws IOException {
File fileFrom = new File(from);
File fileTo = new File(to);

FileInputStream input = null;
FileOutputStream output = null;
try {//字节流:
//输入流:File--FileInputStream--read;
//输出流:File--FileOutputStream--write;
byte[] buf = new byte[(int)fileFrom.length()];
input = new FileInputStream(fileFrom);
input.read(buf);

output = new FileOutputStream(fileTo,true); //true:把文件内容追加到目标文件内容的后面
output.write(buf);
}catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}finally{
input.close();
output.close();
}
}

}


//高级文件流,以字符形式,传输效率更高,但是有局限性,有些地方只能用字节流;

private void copySuper(String source,String target) throws IOException {
File sourcefile = new File(source);
File targetfile = new File(target);
InputStream ist = null;
InputStreamReader isr = null;
BufferedReader brd = null;

OutputStream ost = null;
OutputStreamWriter osw = null;
BufferedWriter bwt = null;
char[] cbuf = new char[100];
try {/*字符流:将文件读入到高级输入流中:sourceFile/PathName--FileInputStream
--InputStreamReader--BufferReader--read*/
/*从高级输出流中读出数据到指定文件夹:targetfile/PathName--FileOutputStream
--OutputStreamWriter--BufferedWriter--write*/
ist = new FileInputStream(sourcefile);
isr = new InputStreamReader(ist);
brd = new BufferedReader(isr);
brd.read(cbuf);
String str = new String(cbuf);
System.out.println(str);
ost = new FileOutputStream(targetfile,true);
osw = new OutputStreamWriter(ost);
bwt = new BufferedWriter(osw);
bwt.write(cbuf);
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally{
brd.close();
isr.close();
ist.close();
bwt.close();
osw.close();
ost.close();
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值