小弟新手,不会哦

解决方案 »

  1.   

    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.InputStream;public class FileUtils { /**
     * 复制文件
     * 
     * @param source
     *            源文件
     * @param destination
     *            目标文件
     * @return 失败文件个数
     */
    public static int copy(File source, File destination) { if (source == null || destination == null) {
    throw new IllegalArgumentException("The File must not be null");
    } int error = 0;
    if (source.isDirectory()) {
    File outDir = new File(destination.getAbsolutePath() + File.separator + source.getName());
    if (!outDir.mkdirs()) {
    error++;
    } // 迭代子文件
    for (File child : source.listFiles()) {
    error += copy(child, new File(outDir.getAbsolutePath(), child.getName()));
    }
    } else {
    try {
    InputStream in = new FileInputStream(source); // 写文件
    if (!write(in, destination)) {
    error++;
    } } catch (Exception e) {
    error++;
    }
    }
    return error;
    } /**
     * 将流写入到文件
     * 
     * @param source
     *            输入流
     * @param destination
     *            目标文件
     * @return 写入文件成功与否
     */
    public static boolean write(InputStream source, File destination) {

    if (source == null || destination == null) {
    throw new IllegalArgumentException("The InputStream and File must not be null");
    }

    boolean flag = false;
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try {
    bis = new BufferedInputStream(source);
    bos = new BufferedOutputStream(new FileOutputStream(destination)); byte[] buff = new byte[1024 * 1024];
    int len = -1;
    while ((len = bis.read(buff)) != -1) {
    bos.write(buff, 0, len);
    }
    bos.flush(); flag = true;
    } catch (Exception e) { } finally {
    try {
    // 关闭流
    if (bos != null) {
    bos.close();
    }
    if (bis != null) {
    bis.close();
    }
    } catch (Exception e) { }
    } return flag; } /**
     * 获取文件扩展名
     * 
     * @param file
     *            文件
     * @return 文件扩展名
     */
    public static String getFileExtensions(File file) {
    String fileName = file.getName();
    if (fileName.lastIndexOf(".") == -1) {
    return "";
    } else {
    return fileName.substring(fileName.lastIndexOf(".") + 1);
    }
    } /**
     * 统一文件路径
     * 
     * @param path
     *            原始路径
     * @return 格式化输出路径
     */
    public static String formatPath(String path) {
    if (path == null) {
    return null;
    } // 将所有"\"替换为"/"
    path = path.replaceAll("\\\\{1,}", "/");
    // 将所有重复"/"替换为单"/"
    path = path.replaceAll("/{2,}", "/");
    if (path.endsWith("/")) {
    path = path.substring(0, path.lastIndexOf("/"));
    } return path;
    }
    }
    试试看