使用字节流复制文件
代码如下:
- public static void main(String[] args){
- BufferedReader bufr=null;
- BufferedWriter bufw=null;
- try {
- //用转换流将字节流转换为字符流,并加入缓冲区
- bufr=new BufferedReader(new InputStreamReader(new FileInputStream("abc.txt")));
- //用转换流将字符流转换为字节流,并加入缓冲
- bufw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream("abc1.txt")));
- String line=null;
- //读取要复制的文件,并写入一个文件中
- while((line=bufr.readLine())!=null){
- bufw.write(line);
- bufw.newLine();
- bufw.flush();
- }
- } catch (Exception e) {
- throw new RuntimeException("文件复制失败!");
- }
- finally{
- try {
- //关闭读取流
- if(bufr!=null)
- bufr.close();
- } catch (IOException e) {
- throw new RuntimeException("读取流关闭失败!");
- }
- try {
- //关闭写入流
- if(bufw!=null)
- bufw.close();
- } catch (IOException e) {
- throw new RuntimeException("写入流关闭失败!");
- }
- }
- }
- }
复制代码
|