Here you can find the source of copyFiles(File sourceFile, File targetDir)
Parameter | Description |
---|---|
sourceFile | a parameter |
targetDir | a parameter |
public static void copyFiles(File sourceFile, File targetDir)
//package com.java2s; /* // w w w . j a v a2 s . c o m * Licensed to the soi-toolkit project under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The soi-toolkit project licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class Main { /** * Copies an existing structure to a new destination. * * @param sourceFile * @param targetDir */ public static void copyFiles(File sourceFile, File targetDir) { copyFiles(sourceFile, sourceFile, targetDir); } public static void copyFiles(File rootDir, File sourceFile, File targetDir) { File[] files = sourceFile.listFiles(); if (files != null) { for (File file : files) { String relativePath = getRelativePath(file, rootDir); File target = new File(targetDir + "/" + relativePath); if (!target.exists() && file.isHidden() == false) { if (file.isDirectory()) { target.mkdir(); copyFiles(rootDir, file, targetDir); } else { copyFile(file, target); } } } } } /** * Returns the relative path. * * @param file * @param srcDir * @return the relative path */ public static String getRelativePath(File file, File srcDir) { String base = srcDir.getPath(); String filePath = file.getPath(); String relativePath = new File(base).toURI().relativize(new File(filePath).toURI()).getPath(); return relativePath; } /** * Copy a file to new destination. * * @param srcFile * @param destFile */ public static void copyFile(File srcFile, File destFile) { OutputStream out = null; InputStream in = null; try { if (!destFile.getParentFile().exists()) destFile.getParentFile().mkdirs(); in = new FileInputStream(srcFile); out = new FileOutputStream(destFile); // Transfer bytes from in to out byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); } catch (IOException e) { throw new RuntimeException(e); } } }