1、关闭eclipse,然后使用任意压缩软件,把eclipse文件夹及文件夹下的所有压缩缩成一个eclipse.zip 保存到D盘下面。
package exce08;
import java.io.*;
public class homework01 {
public static void main(String[] args) {
// TODO 自动生成的方法存根
String srcFileName = "D:\\Eclipse\\eclipse.zip";//需要复制的文件目录
String targetFileName = "D:\\target.zip";//需要复制到哪里
InputStream inStream = null;
try
{
inStream = new FileInputStream(srcFileName);
} catch (FileNotFoundException e)
{
System.err.println("读取文件[" + srcFileName + "]发生错误" + "\r\n"+ e.getCause());
return;}
File targetFile = new File(targetFileName);
OutputStream outStream = null;
try
{
targetFile.createNewFile();
outStream = new FileOutputStream(targetFile);
byte[] by = new byte[1024];
while (inStream.available() > 0)
{
inStream.read(by);
outStream.write(by);
}
} catch (IOException e)
{
System.err.println("创建文件[" + targetFileName + "]发生错误" + "\r\n"+ e.getCause());
} finally
{
if (null != inStream)
{
try
{
inStream.close();
} catch (IOException e)
{
System.err.println(e.getCause());}
}
if (null != outStream)
{
try
{
outStream.flush();
} catch (IOException e)
{
System.err.println(e.getCause());
}
try
{
outStream.close();
} catch (IOException e)
{
System.err.println(e.getCause());
}
}
}
System.out.println("复制完毕!");
}
}
2、使用Path和Files工具类编写一个FilesCopy类,该类包含一个静态方法filesCopy(Path from,Path to),实现把from目录中的文件(文件包括:文件、子文件夹及子文件夹中的文件)复制到to目录中。
package exce08;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
public class FileCopy {
public static void filesCopy(Path from,Path to) throws IOException{
long startTime = System.currentTimeMillis();
final Path destPath = Paths.get(to.toString(), from.toFile().getName());
//检查源文件是否存在
if(Files.notExists(from)){
System.out.println("源文件不存在");
System.exit(1);
}
//如果目标文件不存在则创建
if(Files.notExists(destPath)){
Files.createDirectories(destPath);
}
Files.walkFileTree(from, new SimpleFileVisitor<Path>() {
@Override
// 文件处理,将文件夹也一并处理,简洁些
public FileVisitResult visitFile(Path file,
BasicFileAttributes attrs) throws IOException {
Path dest = destPath.resolve(from.relativize(file));
// 如果说父路径不存在,则创建
if (Files.notExists(dest.getParent())) {
Files.createDirectories(dest.getParent());
}
//copy方法只能复制不存在的路径
Files.copy(file, dest);
/*复制并覆盖的方法
Files.copy(file, dest, StandardCopyOption.REPLACE_EXISTING);
*/
return FileVisitResult.CONTINUE;
}
});
long endTime = System.currentTimeMillis();
System.out.println("复制成功!耗时:" + (endTime - startTime) + "ms");
}
public static void main(String[] args) {
Path from = Paths.get("D:\\Data");
Path to = Paths.get("D:\\Demo");
try {
filesCopy(from,to);
} catch (IOException e) {
e.printStackTrace();
}
}
}
参考bolg:
Path和Files工具类
本题参考代码