首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

!关于文件复制的有关问题

2011-12-25 
高手请进!关于文件复制的问题?我想实现将F盘的一个文件复制的到E盘,不知道我错在哪里,没有成功。请高手帮忙

高手请进!关于文件复制的问题?
我想实现将F盘的一个文件复制的到E盘,不知道我错在哪里,没有成功。请高手帮忙看一下。
代码如下:
package   src;
import   java.io.*;

public   class   CopyFile  
{
public   static   void   copy(String   src,String   dest)
{
        try
        {
              FileInputStream   infile=new   FileInputStream(src);
               
                        InputStreamReader   x=new   InputStreamReader(infile);
                        BufferedReader   y=new   BufferedReader(x);
                       
              File   newfile=new   File(dest);
                      if(!newfile.exists())
                      {
                              newfile.createNewFile();
                              FileOutputStream   outfile=new   FileOutputStream(newfile);
                              OutputStreamWriter   j=new   OutputStreamWriter(outfile);
                              BufferedWriter   m=new   BufferedWriter(j);
                              String   s;
                              while((s=y.readLine())!=null)
                              {
                                  m.write(s);
                              }
                              outfile.close();
                      }
                      infile.close();
                   
        }
        catch(Exception   e)
        {
        e.printStackTrace();
        }
}
       
       
        public   static   void   main(String   arg[])
        {
                String   src= "f:\\4.txt ";
                String   dest= "e:\\5.txt ";
                copy(src,dest);
        }
}

------解决方案--------------------


在操作文件时要注意一点就是正确的关闭流,你的问题是BufferedWriter没有正确地关闭,你先关闭了FileOutputStream,所以缓冲在内存中的文件内容根本没有写到目标文件中,在写完文件后应先从高层流到低层流一级一级的关闭,在本例中关闭顺序:BufferedWriter-> OutputStreamWriter-> FileOutputStream
然后是输入流,顺序一样。
[解决办法]
......
outfile.close();
outfileclose了
但是 bufferedWriter没有close

热点排行