/**
 * 复制整个文件夹内容
 * 
 * @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);
}
}
}

解决方案 »

  1.   

    我的问题是:byte[] b = new byte[1024];这句,是建一个1024字节的数组b,如果要是我要复制的文件超出1024个字节是否还能正常复制成功,我测试了是可以正常复制的但是我搞不清,为什么能够成功呢?
      

  2.   

    while ((len = input.read(b)) != -1) // 把temp读入到b字节数组中。
    {
    output.write(b, 0, len); // 把字节数组b内容写入输出流output中
    }
    这里有循环,只要len值不是-1就证明读到东西了,长度是len,然后把len长度的东西写到文件里.
      

  3.   

    while ((len = input.read(b)) != -1) // 把temp读入到b字节数组中。
    {
    output.write(b, 0, len); // 把字节数组b内容写入输出流output中
    }
    这个循环可以一直读你的文件,如果b读满了就会写到文件里,input.read(b)返回的是读到的字节数,output.write(b,0,len);是把读到的字节数写到文件里,读了多少就写多少.
      

  4.   

    建议,使用InputStream和OutputStream时,都转换为BufferedInputStream和BufferedOutputStream,当很多文件的时候,你会发现速度差距很大~BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));