public class CopyFile {
public boolean copy(String from, String to) throws IOException {
int bytesum=0;
int byteread=0;
URL url = new URL(from);
URLConnection conn = url.openConnection();
InputStream inStream = conn.getInputStream();
FileOutputStream fs=new FileOutputStream(to);
byte[] buffer =new byte[1444]; int length; while ((byteread=inStream.read(buffer))!=-1) {
bytesum+=byteread; System.out.println(bytesum);
fs.write(buffer,0,byteread);
} return true;
}
其中 to是一个Path,如:f:/1/2/3/3/xxxx.jpg,硬盘上没有这个目录,怎么做才能创建目录呀?
就是不能创建目录吧?
IOException {
File file = new File(filePath);
if (!file.exists()) {
file.mkdirs();
}
file = new File(filePath + "\\" + fileName);
if(!file.exists()){
file.createNewFile();
}
}
调用方法:
public static void main(String[] as) { try {
creatFilePath("F:\\a\\a1\\a11","a.txt");
}
catch (IOException ex) {
ex.printStackTrace();
}
}
File file=new File("f:\\1");
file.mkdir();
会执行成功,即能成功新建目录。但是如果f盘没有“1”文件夹,而楼主想建立f:\1\2这个目录,则像上面的代码不会成功。必须新建立1目录,然后再建2目录。所以如果楼主要建立“f:/1/2/3/3/”目录,应执行以下代码:File file=new File("f:\\1");
file.mkdir();File file=new File("f:\\1\\2");
file.mkdir();File file=new File("f:\\1\\2\\3");
file.mkdir();