黑马程序员技术交流社区
标题:
帮忙看看 问题在哪
[打印本页]
作者:
NO?
时间:
2014-4-3 01:08
标题:
帮忙看看 问题在哪
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Testk {
public static void main(String[] args) throws IOException {
copy("G:\\come");
}
/**
* @param string
*/
public static void copy(String string) {
File file = new File(string);
BufferedInputStream fim = null;
BufferedOutputStream fo = null;
File[]fi1=File.listRoots();
for (File fi:fi1){////////////为什么只能执行到这里?
if (fi.isFile()) {
String str = fi.getAbsolutePath();
try {
fim = new BufferedInputStream(new FileInputStream(str));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
fo = new BufferedOutputStream(new FileOutputStream("E"+str.substring(1)));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int ch = 0;
try {
while ((ch = fim.read()) != -1) {
fo.write((char) ch);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (file.isDirectory()) {
copy(string);
}
}
}
}
}
作者:
ehuashao
时间:
2014-4-3 13:02
public class Testk {
public static void main(String[] args) throws IOException {
copy("F:\\come");
}
/**
* @param string
*/
public static void copy(String string) {
File file = new File(string);
BufferedInputStream fim = null;
BufferedOutputStream fo = null;
File[] fi1=file.listFiles();
for (File fi:fi1){////////////为什么只能执行到这里?
if (fi.isFile()) {
String str = fi.getAbsolutePath();
try {
fim = new BufferedInputStream(new FileInputStream(str));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
String path =str.substring(1);
fo = new BufferedOutputStream(new FileOutputStream(new File("E"+path)));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int ch ;
try {
while ((ch = fim.read()) != -1) {
fo.write(ch);
}
fo.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else if (fi.isDirectory()) {
String path =fi.getAbsolutePath().substring(1);
new File("E"+path).mkdir();
copy(string+"\\"+fi.getName());
}
}
}
}
代码中加红线的第一句,FileOutputStream对象后面不管输出地方有没有已经建立好的文件或目录,还是用file新建一个,以免忘了提前建立文件或目录出错。
红线第二处代码,当检索到的file为目录时,要先在输出的盘符里建立相对应的目录,然后把当前目录迭代调用,如你代码。copy(string)那么它迭代的永远是G盘的come目录。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2