本帖最后由 张聪珉 于 2013-8-23 13:39 编辑
复制一个带内容的文件夹到某个盘符(假设E盘)根目录下,以下是我写的代码,大家帮忙看下我这个做法有哪些地方不妥,还有注释那部分我填字符串“E:\\”报异常啊,如果换成“E:\\ java”它就会创建一个java的文件,我郁闷啊。。。。。- import java.io.BufferedInputStream;
- import java.io.BufferedOutputStream;
- import java.io.BufferedWriter;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.OutputStream;
- import java.util.ArrayList;
- import java.util.List;
- public class Copyfile {
- private static String f;
- /**
- * @param args
- */
- public static void main(String[] args) throws IOException{
- File dir=new File("D:\\Java0806");
- List<File> li=new ArrayList<File>();
- fileToList(dir,li);
-
- File file=new File();//这里我应该怎么填,才能复制到某个盘符或者文件夹里???????
- writeToFile(li, file);
- }
- private static void writeToFile(List<File> li, File file) throws IOException {
- // TODO Auto-generated method stub
- BufferedOutputStream bufo = null;
- BufferedInputStream bufi=null;
- try {
- bufo=new BufferedOutputStream(new FileOutputStream(file));
-
- for(File f : li){
- bufi=new BufferedInputStream(new FileInputStream(f));
- byte[] b = new byte[1024];
- bufi.read(b);
- bufo.write(b, 0, b.length);
- }
- } catch (IOException e) {
- // TODO: handle exception
- throw e;
- } finally{
- try{
- if(bufo!=null)
- bufo.close();
- }
- catch (IOException e){
- throw e;
- }
- try{
- if(bufi!=null)
- bufi.close();
- }
- catch (IOException e){
- throw e;
- }
- }
-
-
- }
- private static void fileToList(File dir, List<File> li) {
- // TODO Auto-generated method stub
- File[] files = dir.listFiles();
- for(File file:files){
- if(file.isFile())
- li.add(file);
- else
- fileToList(file,li);
- }
-
-
- }
- }
复制代码 |