日期:2014-05-20  浏览次数:20667 次

大家来帮我看看这个文件复制函数
/**
  *   复制整个文件夹内容
  *  
  *   @param   oldPath
  *                         源文件目录路径   如:c:/fqf
  *   @param   newPath
  *                         目的文件路径   如:f:/fqf/ff
  *   @return   是否成功
  */
public   void   copyFolder(String   oldPath,   String   newPath,   JTextArea   textarea)
{
(new   File(newPath)).mkdirs();   //   如果目的文件夹不存在   则建立目的文件夹
File   old   =   new   File(oldPath);   //   建立源文件夹文件对象   old
String[]   files   =   old.list();   //   返回源文件夹文件列表   files数组
File   temp   =   null;   //   建立一临时文件对象   temp
for   (int   i   =   0;   i   <   files.length;   i++)
{
if   (oldPath.endsWith(File.separator))   //   如果文件目录后有“/”号就把把这个文件赋给temp对象。
{
temp   =   new   File(oldPath   +   files[i]);
}   else
//   如果文件目录后没有“/”号就加上“/”赋值给temp对象。
{
temp   =   new   File(oldPath   +   File.separator   +   files[i]);
}
if   (temp.isFile())   //   如果temp是文件
{
try
{
FileInputStream   input   =   new   FileInputStream(temp);//   建立文件输入流input(temp)
FileOutputStream   output   =   new   FileOutputStream(newPath//   建立文件输出流output(目的路径下)
+   "/ "   +   (temp.getName()).toString());
byte[]   b   =   new   byte[1024];//   建立一个字节数组   b   来放临时文件(temp)流。
int   len;
jTextArea.append( "正在复制文件 "   +   temp.getName()   +   "\n ");
this.repaint();
while   ((len   =   input.read(b))   !=   -1)   //   把temp读入到b字节数组中。
{
output.write(b,   0,   len);   //   把字节数组b内容写入输出流output中
}
output.flush();//   刷新流
output.close();//   关闭流
input.close();//   关闭流
}   catch   (FileNotFoundException   e)
{
System.out.println( "找不到文件 ");
}   catch   (IOException   e)
{
System.out.println( "输入输出异常 ");
}
}
if   (temp.isDirectory())//   如果是子文件夹,则递归调用。
{
copyFolder(oldPath   +   "/ "   +   files[i],   newPath   +   "/ "   +   files[i],
textarea);
}
}
}


------解决方案--------------------
mark
------解决方案--------------------
while ((len = input.read(b)) != -1) // 把temp读入到b字节数组中。
{
output.write(b, 0, len); // 把字节数组b内容写入输出流output中
}
这里有循环,只要len值不是-1就证明读到东西了,长度是len,然后把len长度的东西写到文件里.
------解决方案--------------------
while ((len = input.read(b)) != -1) // 把temp读入到b字节数组中。
{
output.write(b, 0, len); // 把字节数组b内容写入输出流output中
}
这个循环可以一直读你的文件,如果b读满了就会写到文件里,input.read(b)返回的是读到的字节数,output.write(b,0,len);是把读到的字节数写到文件里,读了多少就写多少.
------解决方案--------------------
因为你写了循环了 。所以会一直读取1024字节的数据存放到数组里 然后写到另一个文件中。。 直到读完为止!