代码很简单,请看注释标签。
public void copyFolder(String oldPath, String newPath) {
try {
new File(newPath).mkdirs();
File a=new File(oldPath);
String[] file=a.list();
File temp=null;
for (int i = 0; i < file.length; i++) {
if(oldPath.endsWith(File.separator)){
temp=new File(oldPath+file[i]);
}else{
temp=new File(oldPath+File.separator+file[i]);
}
if(temp.isFile()){
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(newPath + "/" + //问题1:
(temp.getName()).toString());
byte[] b = new byte[1024 * 5]; //问题2:
int len;
while ((len = input.read(b)) != -1) {
output.write(b, 0, len);
}
output.flush();
output.close();
input.close();
}
if(temp.isDirectory()){//如果是子文件夹
copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]);
}
}
}catch (Exception e) {
message = "复制整个文件夹内容操作出错";
}
}问题1:为什么是“/”而不是“\”这个路径符号呢?
问题2:这里byte[]的大小可以随便设置的吗?下面 While 循环中每次都是读取一个1字节?(如果read()方法一次性最多能读 1024*5 大小的数据,那么如果这个文件超过 1024*5 的大小怎么办呢? 也就是说,它的内部会修改偏移量,第二次的读取则从偏移量开始咯?那么byte[]的大小为什么不设置的越大越好呢?)
public void copyFolder(String oldPath, String newPath) {
try {
new File(newPath).mkdirs();
File a=new File(oldPath);
String[] file=a.list();
File temp=null;
for (int i = 0; i < file.length; i++) {
if(oldPath.endsWith(File.separator)){
temp=new File(oldPath+file[i]);
}else{
temp=new File(oldPath+File.separator+file[i]);
}
if(temp.isFile()){
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(newPath + "/" + //问题1:
(temp.getName()).toString());
byte[] b = new byte[1024 * 5]; //问题2:
int len;
while ((len = input.read(b)) != -1) {
output.write(b, 0, len);
}
output.flush();
output.close();
input.close();
}
if(temp.isDirectory()){//如果是子文件夹
copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]);
}
}
}catch (Exception e) {
message = "复制整个文件夹内容操作出错";
}
}问题1:为什么是“/”而不是“\”这个路径符号呢?
问题2:这里byte[]的大小可以随便设置的吗?下面 While 循环中每次都是读取一个1字节?(如果read()方法一次性最多能读 1024*5 大小的数据,那么如果这个文件超过 1024*5 的大小怎么办呢? 也就是说,它的内部会修改偏移量,第二次的读取则从偏移量开始咯?那么byte[]的大小为什么不设置的越大越好呢?)
new InputStreamReader(
new FileInputStream(file1)));
BufferedWriter bw=new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(desti)));[code]
你可以用这个,一行行的读,效率也快
2、byte[]的大小不可以随便设置。While循环中每次都是input流里的所有字节流。超过会报越界错。不是越大越好,太大有浪费和效率问题,刚刚大最好,但这里无法保证,所以设置差不多大。