Example usage for java.io File renameTo

List of usage examples for java.io File renameTo

Introduction

In this page you can find the example usage for java.io File renameTo.

Prototype

public boolean renameTo(File dest) 

Source Link

Document

Renames the file denoted by this abstract pathname.

Usage

From source file:edu.lternet.pasta.datapackagemanager.DataPackageArchive.java

/**
 * Generate an "archive" of the data package by parsing and retrieving
 * components of the data package resource map
 * //w  w w .  ja  v  a2 s  .c om
 * @param scope
 *          The scope value of the data package
 * @param identifier
 *          The identifier value of the data package
 * @param revision
 *          The revision value of the data package
 * @param map
 *          The resource map of the data package
 * @param authToken
 *          The authentication token of the user requesting the archive
 * @param transaction
 *          The transaction id of the request
 * @return The file name of the data package archive
 * @throws Exception
 */
public String createDataPackageArchive(String scope, Integer identifier, Integer revision, String userId,
        AuthToken authToken, String transaction) throws Exception {

    String zipName = transaction + ".zip";
    String zipPath = tmpDir + "/";

    EmlPackageId emlPackageId = new EmlPackageId(scope, identifier, revision);

    StringBuffer manifest = new StringBuffer();

    Date now = new Date();
    manifest.append("Manifest file for " + zipName + " created on " + now.toString() + "\n");

    DataPackageManager dpm = null;

    /*
     * It is necessary to create a temporary file while building the ZIP archive
     * to prevent the client from accessing an incomplete product.
     */
    String tmpName = DigestUtils.md5Hex(transaction);
    File zFile = new File(zipPath + tmpName);

    if (zFile.exists()) {
        String gripe = "The resource " + zipName + "already exists!";
        throw new ResourceExistsException(gripe);
    }

    try {
        dpm = new DataPackageManager();
    } catch (Exception e) {
        logger.error(e.getMessage());
        e.printStackTrace();
        throw e;
    }

    FileOutputStream fOut = null;

    try {
        fOut = new FileOutputStream(zFile);
    } catch (FileNotFoundException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    }

    if (dpm != null && fOut != null) {

        String map = null;

        try {
            map = dpm.readDataPackage(scope, identifier, revision.toString(), authToken, userId);
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            throw e;
        }

        Scanner mapScanner = new Scanner(map);

        ZipOutputStream zOut = new ZipOutputStream(fOut);

        while (mapScanner.hasNextLine()) {

            FileInputStream fIn = null;
            String objectName = null;
            File file = null;

            String line = mapScanner.nextLine();

            if (line.contains(URI_MIDDLE_METADATA)) {

                try {
                    file = dpm.getMetadataFile(scope, identifier, revision.toString(), userId, authToken);
                    objectName = emlPackageId.toString() + ".xml";
                } catch (ClassNotFoundException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                } catch (SQLException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                } catch (Exception e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                }

                if (file != null) {
                    try {
                        fIn = new FileInputStream(file);
                        Long size = FileUtils.sizeOf(file);
                        manifest.append(objectName + " (" + size.toString() + " bytes)\n");
                    } catch (FileNotFoundException e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    }
                }

            } else if (line.contains(URI_MIDDLE_REPORT)) {

                try {
                    file = dpm.readDataPackageReport(scope, identifier, revision.toString(), emlPackageId,
                            authToken, userId);
                    objectName = emlPackageId.toString() + ".report.xml";
                } catch (ClassNotFoundException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                } catch (SQLException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                }

                if (file != null) {
                    try {
                        fIn = new FileInputStream(file);
                        Long size = FileUtils.sizeOf(file);
                        manifest.append(objectName + " (" + size.toString() + " bytes)\n");
                    } catch (FileNotFoundException e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    }
                }

            } else if (line.contains(URI_MIDDLE_DATA)) {

                String[] lineParts = line.split("/");
                String entityId = lineParts[lineParts.length - 1];
                String dataPackageResourceId = DataPackageManager.composeResourceId(ResourceType.dataPackage,
                        scope, identifier, revision, null);
                String entityResourceId = DataPackageManager.composeResourceId(ResourceType.data, scope,
                        identifier, revision, entityId);

                String entityName = null;
                String xml = null;

                try {
                    entityName = dpm.readDataEntityName(dataPackageResourceId, entityResourceId, authToken);
                    xml = dpm.readMetadata(scope, identifier, revision.toString(), userId, authToken);
                    objectName = dpm.findObjectName(xml, entityName);
                    file = dpm.getDataEntityFile(scope, identifier, revision.toString(), entityId, authToken,
                            userId);
                } catch (UnauthorizedException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                    manifest.append(objectName + " (access denied)\n");
                } catch (ResourceNotFoundException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                } catch (SQLException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                } catch (Exception e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                }

                if (file != null) {
                    try {
                        fIn = new FileInputStream(file);
                        Long size = FileUtils.sizeOf(file);
                        manifest.append(objectName + " (" + size.toString() + " bytes)\n");
                    } catch (FileNotFoundException e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    }
                }

            }

            if (objectName != null && fIn != null) {

                ZipEntry zipEntry = new ZipEntry(objectName);

                try {
                    zOut.putNextEntry(zipEntry);

                    int length;
                    byte[] buffer = new byte[1024];

                    while ((length = fIn.read(buffer)) > 0) {
                        zOut.write(buffer, 0, length);
                    }

                    zOut.closeEntry();
                    fIn.close();

                } catch (IOException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                }

            }

        }

        // Create ZIP archive manifest
        File mFile = new File(zipPath + transaction + ".txt");
        FileUtils.writeStringToFile(mFile, manifest.toString());
        ZipEntry zipEntry = new ZipEntry("manifest.txt");

        try {

            FileInputStream fIn = new FileInputStream(mFile);
            zOut.putNextEntry(zipEntry);

            int length;
            byte[] buffer = new byte[1024];

            while ((length = fIn.read(buffer)) > 0) {
                zOut.write(buffer, 0, length);
            }

            zOut.closeEntry();
            fIn.close();

        } catch (IOException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }

        // Close ZIP archive
        zOut.close();

        FileUtils.forceDelete(mFile);

    }

    File tmpFile = new File(zipPath + tmpName);
    File zipFile = new File(zipPath + zipName);

    // Copy hidden ZIP archive to visible ZIP archive, thus making available
    if (!tmpFile.renameTo(zipFile)) {
        String gripe = "Error renaming " + tmpName + " to " + zipName + "!";
        throw new IOException();
    }

    return zipName;

}

From source file:com.f9g4.webapp.servicesFacade.impl.UploadFacadeApacheCommonsUploadImpl.java

public boolean upload(UploadProperties uploadDetails, int uploadMode, UploadResult result) {
    int exitVal;//from   ww w . ja  v a2  s .c o  m
    boolean isFailedProcessing = false;
    //check the folder, if not exist create it.=================
    uploadMode = 3;
    System.out.println("mode ");
    logger.trace("Beginning");

    File folder = new File(profileLocation);
    File folder_100x100 = new File(profileLocation_100);
    File folder_400x400 = new File(profileLocation_400);
    File folder_bigimage = new File(profileLocation_bigimage);
    File folder_source = new File(profileLocation_source);
    //Add folder for files
    File folder_files = new File(profileLocation_files);
    if (!folder.exists())
        folder.mkdir();
    if (!folder_100x100.exists())
        folder_100x100.mkdir();
    if (!folder_400x400.exists())
        folder_400x400.mkdir();
    if (!folder_bigimage.exists())
        folder_bigimage.mkdir();
    if (!folder_source.exists())
        folder_source.mkdir();
    if (!folder_files.exists())
        folder_files.mkdir();

    //      User u = userDAO.getUser(username);

    FileOutputStream fos = null;
    int extIndex = uploadDetails.getFiledata().getOriginalFilename().lastIndexOf('.');
    //fileName = file.name.substr(0, extIndex);
    String original_ext = uploadDetails.getFiledata().getOriginalFilename().substring(extIndex,
            uploadDetails.getFiledata().getOriginalFilename().length());
    //normalize file extension 06/11/2013
    original_ext = original_ext.toLowerCase(); //change to lower case
    if (extIndex != -1 && uploadMode != 3) //skip the ext check when uploadMode is files 
    {
        //if the extension is pdf, then change to AI
        if (original_ext.equals(".pdf"))
            original_ext = ".ai";
        if (original_ext.equals(".jpeg")) //if the extension equals to jpeg, reset to jpg
            original_ext = ".jpg";
    }
    //create filename
    final String uuid = UUID.randomUUID().toString();
    String filename = profileLocation + uuid + original_ext;
    /* 
    this.fileName=uuid + original_ext;
    this.fileName_size_100=UUID.randomUUID().toString()+".jpg";
    this.fileName_size_400=UUID.randomUUID().toString()+".jpg";
    this.fileName_size_original=UUID.randomUUID().toString()+".jpg";
    this.originalFileName = uploadDetails.getFiledata().getOriginalFilename();
    */

    //Set value to UploadResult object
    result.setOriginal_ext(original_ext.replace(".", ""));
    result.setFileName(uuid + original_ext);
    result.setFileName_size_100(UUID.randomUUID().toString() + ".jpg");
    result.setFileName_size_400(UUID.randomUUID().toString() + ".jpg");
    result.setFileName_size_original(UUID.randomUUID().toString() + ".jpg");
    result.setOriginalFileName(uploadDetails.getFiledata().getOriginalFilename());

    try {

        File f = new File(filename);
        if (!f.exists()) {
            f.createNewFile();
        }
        //      
        //         if (!f.exists()){
        //            boolean result = f.mkdir();
        //            
        //            if (!result){
        //               System.out.println("Could not create dir");
        //            }
        //            
        //         }

        //         fos = new FileOutputStream("C:\\Users\\kamlesh\\Downloads\\" + uploadDetails.getFiledata().getOriginalFilename().toUpperCase());
        fos = new FileOutputStream(f);

        fos.write(uploadDetails.getFiledata().getBytes());
        fos.flush();
        fos.close();

        //Convert AI files to Jpeg - use Utility along ghost script
        //decide the parameter by uploadMode
        //Mode==1, no watermark; Mode==2, with watermark; Mode==3, files mode. skip the plmsplitter process.

        String runtimecoomand = "";
        if (uploadMode == 1) {
            runtimecoomand = plmsplitter + " " + filename + " " + plmsplitterparameters + " Renderer="
                    + ghostscript;
        } else if (uploadMode == 2) {
            runtimecoomand = plmsplitter + " " + filename + " " + plmsplitterparametersWithWatermark
                    + " Renderer=" + ghostscript;
        } else if (uploadMode == 3) {
            // Do not need to run plmsplitter.
            // Move the file to files folder.
            //get file
            File temp = new File(filename);
            //create new file
            File dest = new File(profileLocation_files + result.getFileName());
            temp.renameTo(dest);
            return true;
        } else {
            runtimecoomand = plmsplitter + " " + filename + " " + plmsplitterparametersWithWatermark
                    + " Renderer=" + ghostscript;
        }

        //Process process= Runtime.getRuntime().exec(runtimecoomand);
        logger.trace("COMPLETE");

        //wait the process finish and continue the program.====================
        try {
            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec(runtimecoomand);

            // any error message?
            StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERR");

            // any output?
            StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUT");

            // kick them off
            errorGobbler.start();
            outputGobbler.start();

            // any error???
            exitVal = proc.waitFor();
            //this.uploadStatus=exitVal;
            if (exitVal != 0)
                isFailedProcessing = true;
            else
                isFailedProcessing = false;
        } catch (Throwable t) {
            t.printStackTrace();
            result.setFailedProcessing(true);
            return false;
        }
        /*try
        {
           process.wait();
        }
        catch (Exception e)
        //catch (InterruptedException e) 
        {
           // TODO Auto-generated catch block
           e.printStackTrace();
        }*/

        logger.trace("READEING FILE LIST");
        File dir = new File(profileLocation);
        FilenameFilter filefilter = new FilenameFilter() {
            public boolean accept(File dir, String name) {
                //if the file extension is .jpg return true, else false
                return name.matches(".*" + uuid + ".*jpg");
            }
        };
        String[] fileList = dir.list(filefilter);
        if (fileList.length <= 0) //if no thumbnails images are created after plmsplitter, it's failed processing.
        {
            isFailedProcessing = true;
        }
        //create a FilenameFilter and override its accept-method
        if (isFailedProcessing) {
            //create the dummy images to thumbnails folder to occupies the file name.
            //get dummy image file
            File dummyImageFile = new File(dummyImage);
            File dest100 = new File(profileLocation_100 + result.getFileName_size_100());
            File dest400 = new File(profileLocation_400 + result.getFileName_size_400());
            File destOriginalSize = new File(profileLocation_bigimage + result.getFileName_size_original());
            FileUtils.copyFile(dummyImageFile, dest100); //100*100
            FileUtils.copyFile(dummyImageFile, dest400); //400*400
            FileUtils.copyFile(dummyImageFile, destOriginalSize); //original image size
            //move the file to error files folder
            File temp = new File(filename);
            //create new file
            File dest = new File(profileLocation_error_files + result.getFileName());
            temp.renameTo(dest);
        } else {
            //move source files==================================
            //get file
            File temp = new File(filename);
            //create new file
            File dest = new File(profileLocation_source + result.getFileName());
            temp.renameTo(dest);
            //move generated jpg files.
            for (int i = 0; i < fileList.length; i++) {
                if (fileList[i].matches(".*400x400.*")) {
                    logger.trace("MOVE " + fileList[i] + " to 400x400 folder");
                    //move to 400x400 folder
                    //get file
                    temp = new File(profileLocation + fileList[i]);
                    //create new file
                    dest = new File(profileLocation_400 + result.getFileName_size_400());
                    temp.renameTo(dest);
                } else if (fileList[i].matches(".*100x100.*")) {
                    logger.trace("MOVE " + fileList[i] + " to 100x100 folder");
                    //move to 100x100 folder
                    //get file
                    temp = new File(profileLocation + fileList[i]);
                    //create new file
                    dest = new File(profileLocation_100 + result.getFileName_size_100());
                    temp.renameTo(dest);
                } else {
                    logger.trace("MOVE " + fileList[i] + " to bigimage folder");
                    //move to original folder
                    //get file
                    temp = new File(profileLocation + fileList[i]);
                    //create new file
                    dest = new File(profileLocation_bigimage + result.getFileName_size_original());
                    temp.renameTo(dest);
                }
            }
        }
        /*Update uploadResult object*/
        result.setUploadStatus(exitVal);
        result.setFailedProcessing(isFailedProcessing);
        return true;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return false;

    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } finally {
        try {
            if (fos != null) {
                fos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // Add Runtime to parse the AI files and convert it to jpg    
}

From source file:com.nridge.connector.common.con_com.crawl.CrawlQueue.java

private void renameQueuePathFileName(String aSrcPathFileName, String aDstPathFileName, boolean aIsSrcRequired)
        throws NSException {
    File srcFile = new File(aSrcPathFileName);
    File dstFile = new File(aDstPathFileName);
    if (srcFile.exists()) {
        if (!srcFile.renameTo(dstFile))
            throw new NSException(
                    String.format("'%s' to '%s': Unable to rename file.", aSrcPathFileName, aDstPathFileName));
    } else {/*from  w  w  w . j  ava  2 s  .  c  o m*/
        if (aIsSrcRequired)
            throw new NSException(String.format("%s: Does not exist.", aSrcPathFileName));
    }
}

From source file:net.coding.program.project.init.create.ProjectCreateFragment.java

@AfterViews
protected void init() {
    projectInfo = new ProjectInfo();
    projectTypeText.setText(currentType);
    imageLoadTool.loadImage(projectIcon, IconRandom.getRandomUrl(), ImageLoadTool.optionsRounded2,
            new SimpleImageLoadingListener() {
                @Override//from w  w w. ja  v  a 2  s.  com
                public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                    if (!isResumed()) {
                        return;
                    }

                    File imageFile = imageLoadTool.imageLoader.getDiskCache().get(imageUri);
                    if (imageFile == null) { // ??umeng??
                        showMiddleToast("");
                        return;
                    }

                    File newFile = new File(imageFile.getPath() + ".png");

                    if (newFile.exists() || imageFile.renameTo(newFile)) {
                        defaultIconUrl = newFile.getPath();
                    } else {
                        defaultIconUrl = imageFile.getPath();
                    }
                }
            });

    projectName.addTextChangedListener(new SimpleTextWatcher() {

        @Override
        public void afterTextChanged(Editable s) {
            updateSendButton();
        }
    });
    Global.popSoftkeyboard(getActivity(), description, false);
}

From source file:au.org.ands.vocabs.toolkit.utils.ToolkitFileUtils.java

/** Compress the files in the backup folder for a project.
 * @param projectId The project ID/*from   w  ww  . j  a v  a2  s .c  o m*/
 * @throws IOException Any exception when reading/writing data.
 */
public static void compressBackupFolder(final String projectId) throws IOException {
    String backupPath = getBackupPath(projectId);
    if (!Files.isDirectory(Paths.get(backupPath))) {
        // No such directory, so nothing to do.
        return;
    }
    String projectSlug = makeSlug(projectId);
    // The name of the ZIP file that does/will contain all
    // backups for this project.
    Path zipFilePath = Paths.get(backupPath).resolve(projectSlug + ".zip");
    // A temporary ZIP file. Any existing content in the zipFilePath
    // will be copied into this, followed by any other files in
    // the directory that have not yet been added.
    Path tempZipFilePath = Paths.get(backupPath).resolve("temp" + ".zip");

    File tempZipFile = tempZipFilePath.toFile();
    if (!tempZipFile.exists()) {
        tempZipFile.createNewFile();
    }

    ZipOutputStream tempZipOut = new ZipOutputStream(new FileOutputStream(tempZipFile));

    File existingZipFile = zipFilePath.toFile();
    if (existingZipFile.exists()) {
        ZipFile zipIn = new ZipFile(existingZipFile);

        Enumeration<? extends ZipEntry> entries = zipIn.entries();
        while (entries.hasMoreElements()) {
            ZipEntry e = entries.nextElement();
            logger.debug("compressBackupFolder copying: " + e.getName());
            tempZipOut.putNextEntry(e);
            if (!e.isDirectory()) {
                copy(zipIn.getInputStream(e), tempZipOut);
            }
            tempZipOut.closeEntry();
        }
        zipIn.close();
    }

    File dir = new File(backupPath);
    File[] files = dir.listFiles();

    for (File source : files) {
        if (!source.getName().toLowerCase().endsWith(".zip")) {
            logger.debug("compressBackupFolder compressing and " + "deleting file: " + source.toString());
            if (zipFile(tempZipOut, source)) {
                source.delete();
            }
        }
    }

    tempZipOut.flush();
    tempZipOut.close();
    tempZipFile.renameTo(existingZipFile);
}

From source file:gov.gtas.job.scheduler.LoaderScheduler.java

private void processInputAndOutputDirectories(Path incomingDir, Path outgoingDir, LoaderStatistics stats) {
    // No hidden files.
    DirectoryStream.Filter<Path> filter = entry -> {
        File f = entry.toFile();
        return !f.isHidden() && f.isFile();
    };/* w ww .  j  av a 2s .co m*/
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(incomingDir, filter)) {

        final Iterator<Path> iterator = stream.iterator();
        List<File> files = new ArrayList<>();
        for (int i = 0; iterator.hasNext() && i < maxNumofFiles; i++) {
            files.add(iterator.next().toFile());
        }
        Collections.sort(files, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR);
        files.stream().forEach(f -> {
            processSingleFile(f, stats);
            f.renameTo(new File(outgoingDir.toFile() + File.separator + f.getName()));
        });
        stream.close();
    } catch (IOException ex) {
        logger.error("IOException:" + ex.getMessage(), ex);
        ErrorDetailInfo errInfo = ErrorHandlerFactory.createErrorDetails(ex);
        errorPersistenceService.create(errInfo);
    }
}

From source file:org.mobisocial.corral.CorralS3Connector.java

Uri downloadAndDecrypt(String ticket, String datestr, String objName, File cachefile, String mykey,
        CorralDownloadFuture future, DownloadProgressCallback callback)
        throws IOException, GeneralSecurityException {
    Log.d(TAG, "-----DOWNLOAD+DECRYPT START-----" + (String.valueOf(System.currentTimeMillis())));
    Log.d(TAG, SERVER_URL + objName);
    Log.d(TAG, "Authorization: AWS " + ticket);
    Log.d(TAG, "Date: " + datestr);

    HttpClient http = new DefaultHttpClient();
    HttpGet get = new HttpGet(SERVER_URL + objName);
    get.addHeader("Authorization", "AWS " + ticket);
    get.addHeader("Date", datestr);
    HttpResponse response = http.execute(get);

    DataInputStream is = new DataInputStream(response.getEntity().getContent());
    long contentLength = response.getEntity().getContentLength();

    if (!cachefile.exists()) {
        File tmpFile = new File(cachefile.getAbsoluteFile() + ".tmp");
        tmpFile.getParentFile().mkdirs();
        try {//www.  java  2 s.  com
            CryptUtil cu = new CryptUtil(mykey);
            cu.InitCiphers();
            FileOutputStream fos = new FileOutputStream(tmpFile);
            cu.decrypt(is, fos, contentLength, callback);
            try {
                is.close();
            } catch (IOException e) {
            }
            try {
                fos.close();
            } catch (IOException e) {
            }

            tmpFile.renameTo(cachefile);

        } catch (IOException e) {
            if (tmpFile.exists()) {
                tmpFile.delete();
            }
            throw e;
        } catch (GeneralSecurityException e) {
            throw e;
        }
    }
    return cachefile.exists() ? Uri.fromFile(cachefile) : null;
}

From source file:me.doshou.admin.maintain.editor.web.controller.OnlineEditorController.java

@RequestMapping("/rename")
public String rename(@RequestParam(value = "path") String path, @RequestParam(value = "newName") String newName,
        RedirectAttributes redirectAttributes) throws IOException {

    String rootPath = sc.getRealPath(ROOT_DIR);
    path = URLDecoder.decode(path, Constants.ENCODING);

    File current = new File(rootPath + File.separator + path);
    File parent = current.getParentFile();
    String parentPath = parent.getAbsolutePath().replace(rootPath, "");

    File renameToFile = new File(parent, newName);
    boolean result = current.renameTo(renameToFile);
    if (result == false) {
        redirectAttributes.addFlashAttribute(Constants.ERROR,
                "??[" + newName + "]/?");
    } else {/*from   ww w  . j ava 2  s.  c om*/
        redirectAttributes.addFlashAttribute(Constants.MESSAGE, "????");
    }

    redirectAttributes.addAttribute("path", parentPath);
    return redirectToUrl(viewName("list"));
}

From source file:com.rover12421.shaka.apktool.lib.AndrolibAj.java

@Around("execution(* brut.androlib.Androlib.buildUnknownFiles(..))" + "&& args(appDir, outFile, meta)")
public void buildUnknownFiles_around(File appDir, File outFile, Map<String, Object> meta) throws Throwable {
    if (meta.containsKey("unknownFiles")) {
        LogHelper.info("Copying unknown files/dir...");

        Map<String, String> files = (Map<String, String>) meta.get("unknownFiles");
        File tempFile = File.createTempFile("buildUnknownFiles", "tmp", outFile.getParentFile());
        tempFile.delete();/*from   w w  w.  ja  v a2  s. com*/
        boolean renamed = outFile.renameTo(tempFile);
        if (!renamed) {
            throw new AndrolibException("Unable to rename temporary file");
        }

        try (ZipFile inputFile = new ZipFile(tempFile);
                FileOutputStream fos = new FileOutputStream(outFile);
                ZipOutputStream actualOutput = new ZipOutputStream(fos)) {
            copyExistingFiles(inputFile, actualOutput, files);
            copyUnknownFiles(appDir, actualOutput, files);
        } catch (IOException ex) {
            throw new AndrolibException(ex);
        } finally {
            // Remove our temporary file.
            tempFile.delete();
        }
    }
}

From source file:hudson.os.solaris.ZFSInstaller.java

/**
 * Migrates $HUDSON_HOME to a new ZFS file system.
 *
 * TODO: do this in a separate JVM to elevate the privilege.
 *
 * @param listener/*from  w w  w. j  a  va2s .  c o m*/
 *      Log of migration goes here.
 * @param target
 *      Dataset to move the data to.
 * @return
 *      false if a migration failed.
 */
private static boolean migrate(TaskListener listener, String target) throws IOException, InterruptedException {
    PrintStream out = listener.getLogger();

    File home = Hudson.getInstance().getRootDir();
    // do the migration
    LibZFS zfs = new LibZFS();
    ZFSFileSystem existing = zfs.getFileSystemByMountPoint(home);
    if (existing != null) {
        out.println(home + " is already on ZFS. Doing nothing");
        return true;
    }

    File tmpDir = Util.createTempDir();

    // mount a new file system to a temporary location
    out.println("Opening " + target);
    ZFSFileSystem hudson = zfs.open(target, ZFSFileSystem.class);
    hudson.setMountPoint(tmpDir);
    hudson.setProperty("hudson:managed-by", "hudson"); // mark this file system as "managed by Hudson"
    hudson.mount();

    // copy all the files
    out.println("Copying all existing data files");
    if (system(home, listener, "/usr/bin/cp", "-pR", ".", tmpDir.getAbsolutePath()) != 0) {
        out.println("Failed to copy " + home + " to " + tmpDir);
        return false;
    }

    // unmount
    out.println("Unmounting " + target);
    hudson.unmount(MountFlags.MS_FORCE);

    // move the original directory to the side
    File backup = new File(home.getPath() + ".backup");
    out.println("Moving " + home + " to " + backup);
    if (backup.exists())
        Util.deleteRecursive(backup);
    if (!home.renameTo(backup)) {
        out.println("Failed to move your current data " + home + " out of the way");
    }

    // update the mount point
    out.println("Creating a new mount point at " + home);
    if (!home.mkdir())
        throw new IOException("Failed to create mount point " + home);

    out.println("Mounting " + target);
    hudson.setMountPoint(home);
    hudson.mount();

    out.println("Sharing " + target);
    try {
        hudson.setProperty("sharesmb", "on");
        hudson.setProperty("sharenfs", "on");
        hudson.share();
    } catch (ZFSException e) {
        listener.error("Failed to share the file systems: " + e.getCode());
    }

    // delete back up
    out.println("Deleting " + backup);
    if (system(new File("/"), listener, "/usr/bin/rm", "-rf", backup.getAbsolutePath()) != 0) {
        out.println("Failed to delete " + backup.getAbsolutePath());
        return false;
    }

    out.println("Migration completed");
    return true;
}