Example usage for org.apache.commons.io FileUtils copyFileToDirectory

List of usage examples for org.apache.commons.io FileUtils copyFileToDirectory

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils copyFileToDirectory.

Prototype

public static void copyFileToDirectory(File srcFile, File destDir) throws IOException 

Source Link

Document

Copies a file to a directory preserving the file date.

Usage

From source file:atg.tools.dynunit.test.configuration.RepositoryConfiguration.java

private void createIdSpaces() throws IOException {
    logger.entry();
    FileUtils.copyFileToDirectory(getIdSpacesTemplate(), atgService);
    logger.exit();
}

From source file:de.fosd.jdime.common.FileArtifact.java

@Override
public final void copyArtifact(final FileArtifact destination) throws IOException {
    assert (destination != null);

    if (destination.isFile()) {
        if (isFile()) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Copying file " + this + " to file " + destination);
                LOG.debug("Destination already exists overwriting: " + destination.exists());
            }//from   w  w w  . ja  v  a2 s. c  o  m

            FileUtils.copyFile(file, destination.file);
        } else {
            throw new UnsupportedOperationException(
                    "When copying to a file, " + "the source must also be a file.");
        }
    } else if (destination.isDirectory()) {
        if (isFile()) {
            assert (destination.exists()) : "Destination directory does not exist: " + destination;
            if (LOG.isDebugEnabled()) {
                LOG.debug("Copying file " + this + " to directory " + destination);
            }
            FileUtils.copyFileToDirectory(file, destination.file);
        } else if (isDirectory()) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Copying directory " + this + " to directory " + destination);
                LOG.debug("Destination already exists overwriting: " + destination.exists());
            }
            FileUtils.copyDirectory(file, destination.file);
        }
    } else {
        LOG.fatal("Failed copying " + this + " to " + destination);
        LOG.fatal("isDirectory(" + this + ") = " + isDirectory());
        LOG.fatal("isDirectory(" + destination + ") = " + destination.isDirectory());
        throw new NotYetImplementedException("Only copying files and directories is supported.");
    }
}

From source file:com.mc.printer.model.panel.task.BuildGuideTask.java

@Override
public Object doBackgrounp() {
    javax.swing.JTabbedPane tabs = AutoPrinterApp.getMainView().getMainWorkPanel();
    if (tabs != null) {
        if (tabs.getSelectedIndex() >= 0) {
            Component selectedcom = tabs.getSelectedComponent();
            if (selectedcom instanceof GuideWork) {
                GuideWork selectPanel = (GuideWork) selectedcom;
                GuideBean presentBeansForm = selectPanel.getBeansForm();

                logger.debug("selected tab:" + selectPanel.getName());
                //?
                GuideBean beansForm;/*  w w  w.  java  2 s  .  c o m*/
                try {
                    beansForm = presentBeansForm.clone();
                } catch (CloneNotSupportedException ex) {
                    logger.error(ex.getMessage());
                    beansForm = presentBeansForm;
                }

                String backGroundImg = beansForm.getBackgoundImg();

                //
                Set<String> imgArray = new HashSet();

                if (backGroundImg != null) {
                    File file = new File(backGroundImg);
                    if (file.exists() && file.isFile()) {
                        beansForm.setBackgoundImg(file.getName());
                        imgArray.add(backGroundImg);
                    } else {
                        beansForm.setBackgoundImg("");
                    }
                } else {
                    beansForm.setBackgoundImg("");
                }

                HashMap<String, GuideCompBean> parameterMap = new HashMap<String, GuideCompBean>();
                HashMap<String, GuideCompBean> parentParameterMap = selectPanel.getSavedForms();
                deepCloneMap(parameterMap, parentParameterMap);

                if (parameterMap.size() > 0) {
                    Set set = parameterMap.keySet();
                    //???
                    List<GuideCompBean> beans = new ArrayList();
                    Iterator it = set.iterator();
                    while (it.hasNext()) {
                        GuideCompBean com = parameterMap.get(it.next().toString());
                        beans.add(com);

                        String pressedIcon = com.getPressedIcon();
                        String icon = com.getIcon();
                        if (pressedIcon != null && !pressedIcon.equals("")) {

                            File pressfile = new File(pressedIcon);
                            if (pressfile.exists() && pressfile.isFile()) {
                                imgArray.add(pressedIcon);
                                com.setPressedIcon(pressfile.getName());
                            } else {
                                com.setPressedIcon("");
                            }

                        }
                        if (icon != null && !icon.equals("")) {
                            File iconfile = new File(icon);
                            if (iconfile.exists() && iconfile.isFile()) {
                                imgArray.add(icon);
                                com.setIcon(iconfile.getName());
                            } else {
                                com.setIcon("");
                            }
                        }
                    }
                    beansForm.setElements(beans);

                    BaseFileChoose fileChoose = new BaseFileChoose("?",
                            new String[] { Constants.MODEL_SUFFIX }, AutoPrinterApp.getMainFrame());
                    String selectedPath = fileChoose.showSaveDialog();
                    if (!selectedPath.trim().equals("")) {

                        //get formname
                        selectedPath = selectedPath + File.separator + beansForm.getGuideName();
                        //String time=DateHelper.format(new Date(), "yyyyMMddHHmmss");
                        String finalZip = selectedPath;
                        if (!selectedPath.endsWith("." + Constants.GUIDE_SUFFIX)) {
                            finalZip = selectedPath + "." + Constants.GUIDE_SUFFIX;
                        }

                        String tempDir = selectedPath + File.separator + Constants.GUIDE_TEMP_DIR;

                        String xmlPath = tempDir + File.separator + beansForm.getGuideName() + ".xml";
                        XMLHelper helper = new XMLHelper(xmlPath, beansForm);
                        try {
                            helper.write();
                        } catch (JAXBException ex) {
                            ex.printStackTrace();
                            logger.error(ex.getMessage());
                            return ex;
                        }

                        File paramFile = new File(xmlPath);
                        if (paramFile.isFile() && paramFile.exists()) {
                            try {
                                logger.info("copy file and zip temp for:" + tempDir + ",total of attached file:"
                                        + imgArray.size());
                                File _temp = new File(tempDir);
                                for (String img : imgArray) {
                                    File imgFile = new File(img);
                                    logger.debug("copy image:" + imgFile.getName());
                                    FileUtils.copyFileToDirectory(imgFile, _temp);
                                }

                                ZipHelper.createZip(tempDir, finalZip);
                                logger.info("zip file successfully.");
                                return "??.\r\n" + finalZip;
                            } catch (IOException ex) {
                                ex.printStackTrace();
                                logger.error(ex.getMessage());
                                return ex;
                            } finally {
                                try {
                                    FileUtils.deleteDirectory(new File(selectedPath));
                                } catch (IOException ex) {
                                    ex.printStackTrace();
                                    logger.error(ex.getMessage());
                                    return ex;
                                }
                            }
                        } else {
                            logger.error("generator faild for:" + xmlPath);
                        }
                    }
                } else {
                    return "??.";
                }
            } else {
                return "??????.";
            }
        } else {
            return "?.";
        }
    } else {
        return "?.";
    }
    return null;
}

From source file:com.legstar.jaxb.AbstractJaxbGenTest.java

/**
 * Check a result against a reference./*from   w  w  w.  j av a2s  . com*/
 * <p/>
 * Here result is a folder as well a reference. In check mode all file are
 * compared in creation mode all reference files are created as copies from
 * the results.
 * <p/>
 * ObjectFactories are not compared because their content is not ordered in
 * a consistent way.
 * 
 * @param refFolder the reference folder (containing reference files)
 * @param resultFolder the result folder (containing generated files)
 * @param extension the files extension to process
 * @throws Exception if something fails
 */
public void check(final File refFolder, final File resultFolder, final String extension) throws Exception {

    if (isCreateReferences()) {
        Collection<File> resultFiles = FileUtils.listFiles(resultFolder, new String[] { extension }, false);
        for (File resultFile : resultFiles) {
            FileUtils.copyFileToDirectory(resultFile, refFolder);
        }
    } else {
        Collection<File> referenceFiles = FileUtils.listFiles(refFolder, new String[] { extension }, false);
        for (File referenceFile : referenceFiles) {
            if (referenceFile.getName().equals("ObjectFactory.java")) {
                continue;
            }
            File resultFile = new File(resultFolder, FilenameUtils.getName(referenceFile.getPath()));
            assertEquals(referenceFile, resultFile);
        }
    }

}

From source file:fm.last.commons.io.LastFileUtilsTest.java

@Test
public void testMoveFileToDirectorySafely_CreateDir() throws IOException {
    // first copy file from data folder to temp folder so it can be moved safely
    File originalFile = dataFolder.getFile("3805bytes.log");
    FileUtils.copyFileToDirectory(originalFile, tempFolder.getRoot());
    File inputFile = new File(tempFolder.getRoot(), originalFile.getName());
    assertTrue(inputFile.getAbsolutePath() + " not found", inputFile.exists());

    // now do the actual moving
    File newDir = new File(tempFolder.getRoot(), "FileUtilsTest");
    assertFalse(newDir.exists()); // dir must not exist
    // copy file over to newdir, creating dir if it doesn't exist
    LastFileUtils.moveFileToDirectorySafely(inputFile, newDir, true);
    assertFalse(inputFile.getAbsolutePath() + " exists", inputFile.exists());
    File movedFile = new File(newDir, inputFile.getName());
    assertTrue(movedFile.getAbsolutePath() + " doesn't exist", movedFile.exists());

    assertEquals(FileUtils.readFileToString(originalFile), FileUtils.readFileToString(movedFile));
}

From source file:com.docd.purefm.utils.PFMFileUtils.java

public static void copyFileToDirectory(@NonNull final GenericFile source, @NonNull final GenericFile target,
        final boolean useCommandLine) throws IOException {
    if (useCommandLine) {
        if (!target.exists()) {
            throw new FileNotFoundException("Target doesn't exist");
        }/*from  w w  w  .  j  a v  a2s  . c o m*/
        if (!target.isDirectory()) {
            throw new IllegalArgumentException("Target is not a directory");
        }
        final boolean result = CommandLine.execute(new CommandCopyRecursively(source, target));
        if (!result) {
            throw new IOException("Move failed");
        }
    } else {
        FileUtils.copyFileToDirectory(source.toFile(), target.toFile());
    }
}

From source file:de.Maxr1998.xposed.maxlock.ui.settings.appslist.AppsListFragment.java

@SuppressLint("WorldReadableFiles")
@Override//from  www.  jav a  2  s . c o  m
public boolean onOptionsItemSelected(MenuItem item) {
    if (pref.getBoolean(Common.ENABLE_PRO, false)) {
        final File prefsPackagesFileShort = new File(Common.PREFS_PACKAGES + ".xml");
        final File prefsPerAppFileShort = new File(Common.PREFS_PER_APP + ".xml");
        final File prefsPackagesFile = new File(getActivity().getApplicationInfo().dataDir + File.separator
                + "shared_prefs" + File.separator + prefsPackagesFileShort);
        final File prefsPerAppFile = new File(getActivity().getApplicationInfo().dataDir + File.separator
                + "shared_prefs" + File.separator + prefsPerAppFileShort);
        final File backupDir = new File(
                Environment.getExternalStorageDirectory() + File.separator + "MaxLock_Backup");

        switch (item.getItemId()) {
        case R.id.toolbar_backup_list:
            File curTimeDir = new File(backupDir + File.separator
                    + new SimpleDateFormat("yyyy-MM-dd-HH.mm.ss", Locale.getDefault())
                            .format(new Date(System.currentTimeMillis()))
                    + File.separator);
            try {
                if (prefsPackagesFile.exists()) {
                    FileUtils.copyFileToDirectory(prefsPackagesFile, curTimeDir);
                    if (prefsPerAppFile.exists())
                        FileUtils.copyFileToDirectory(prefsPerAppFile, curTimeDir);
                } else
                    Toast.makeText(getActivity(), R.string.toast_no_files_to_backup, Toast.LENGTH_SHORT).show();
            } catch (IOException e) {
                Toast.makeText(getActivity(), R.string.toast_backup_restore_exception, Toast.LENGTH_SHORT)
                        .show();
                e.printStackTrace();
            }
            if (curTimeDir.exists() && new File(curTimeDir + File.separator + prefsPackagesFileShort).exists())
                Toast.makeText(getActivity(), R.string.toast_backup_success, Toast.LENGTH_SHORT).show();
            return true;

        case R.id.toolbar_restore_list:
            List<String> list = new ArrayList<>(Arrays.asList(backupDir.list()));
            restoreAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, list);
            restoreDialog = new AlertDialog.Builder(getActivity())
                    .setTitle(R.string.dialog_restore_list_message)
                    .setAdapter(restoreAdapter, new DialogInterface.OnClickListener() {
                        @SuppressLint("InlinedApi")
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            File restorePackagesFile = new File(backupDir + File.separator
                                    + restoreAdapter.getItem(i) + File.separator + prefsPackagesFileShort);
                            File restorePerAppFile = new File(backupDir + File.separator
                                    + restoreAdapter.getItem(i) + File.separator + prefsPerAppFileShort);
                            if (restorePackagesFile.exists()) {
                                try {
                                    //noinspection ResultOfMethodCallIgnored
                                    prefsPackagesFile.delete();
                                    FileUtils.copyFile(restorePackagesFile, prefsPackagesFile);
                                    if (restorePerAppFile.exists()) {
                                        //noinspection ResultOfMethodCallIgnored
                                        prefsPerAppFile.delete();
                                        FileUtils.copyFile(restorePerAppFile, prefsPerAppFile);
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                                getActivity().getSharedPreferences(Common.PREFS_PACKAGES,
                                        Context.MODE_MULTI_PROCESS);
                                getActivity().getSharedPreferences(Common.PREFS_PER_APP,
                                        Context.MODE_MULTI_PROCESS);
                                Toast.makeText(getActivity(), R.string.toast_restore_success,
                                        Toast.LENGTH_SHORT).show();
                                ((SettingsActivity) getActivity()).restart();
                            } else
                                Toast.makeText(getActivity(), R.string.toast_no_files_to_restore,
                                        Toast.LENGTH_SHORT).show();
                        }
                    }).setNegativeButton(android.R.string.cancel, null).show();
            restoreDialog.getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                    try {
                        FileUtils.deleteDirectory(
                                new File(backupDir + File.separator + restoreAdapter.getItem(i)));
                        restoreAdapter.remove(restoreAdapter.getItem(i));
                        restoreAdapter.notifyDataSetChanged();
                    } catch (IOException e) {
                        e.printStackTrace();
                        return false;
                    }
                    return true;
                }
            });
            return true;
        case R.id.toolbar_clear_list:
            //noinspection deprecation
            getActivity().getSharedPreferences(Common.PREFS_PACKAGES, Context.MODE_WORLD_READABLE).edit()
                    .clear().commit();
            //noinspection deprecation
            getActivity().getSharedPreferences(Common.PREFS_PER_APP, Context.MODE_WORLD_READABLE).edit().clear()
                    .commit();
            ((SettingsActivity) getActivity()).restart();
        }
    } else
        Toast.makeText(getActivity(), R.string.toast_pro_required, Toast.LENGTH_SHORT).show();
    return super.onOptionsItemSelected(item);
}

From source file:es.urjc.mctwp.bbeans.research.image.SelectImagesToImport.java

/**
 * Retrieve thumbnails from temp collection and stores its content 
 * into web context user folder. It cleans previous images.
 *///from w w w.j a  va 2  s  .com
private void populateThumbNails() {
    List<ThumbNail> aux = null;
    getSession().cleanUserTempDirectory();

    Command cmd = getCommand(LoadThumbsOfTemporalImages.class);
    ((LoadThumbsOfTemporalImages) cmd).setTempColl(folder);
    cmd = runCommand(cmd);
    aux = ((LoadThumbsOfTemporalImages) cmd).getResult();

    if (aux != null) {

        thumbs = new ArrayList<ThumbSelectItem>();
        for (ThumbNail tn : aux) {

            //Copy content from collection to web context user folder
            try {
                FileUtils.copyFileToDirectory(tn.getContent(), getSession().getThumbDir());
                File th = new File(
                        FilenameUtils.concat(getSession().getRelativeThumbDir(), tn.getContent().getName()));
                tn.setContent(th);

                ThumbSelectItem tsi = new ThumbSelectItem();
                tsi.setThumbId(tn.getId());
                tsi.setPath(tn.getContent().getPath());

                if (tn.getPatInfo() != null) {
                    tsi.setPatName(tn.getPatInfo().getName());
                    tsi.setPatCode(tn.getPatInfo().getCode());
                    tsi.setStdCode(tn.getPatInfo().getStudy());
                }

                thumbs.add(tsi);
            } catch (IOException e) {
            }
        }

        Collections.sort(thumbs);
    }
}

From source file:com.google.gdt.eclipse.designer.core.model.widgets.ClassLoaderTest.java

/**
 * There was regression during 2.3.0 release.
 */// w w w.  j a v a  2 s. c o  m
@DisposeProjectAfter
public void test_gwtInDirectoryWithSpace() throws Exception {
    // remove existing GWT jars from classpath
    ProjectUtils.removeClasspathEntries(m_javaProject, new Predicate<IClasspathEntry>() {
        @Override
        public boolean apply(IClasspathEntry entry) {
            return entry.getPath().toPortableString().contains("gwt-");
        }
    });
    // use GWT jars from directory with spaces
    File gwtDirectory;
    {
        String testLocation = Activator.getDefault().getStateLocation().toPortableString();
        gwtDirectory = new File(testLocation + "/SDK with spaces");
        // copy jars
        String sdkLocation = getGWTLocation_forProject();
        FileUtils.copyFileToDirectory(new File(sdkLocation + "/gwt-user.jar"), gwtDirectory);
        FileUtils.copyFileToDirectory(new File(sdkLocation + "/gwt-dev.jar"), gwtDirectory);
        // add jars into classpath
        m_testProject.addExternalJars(gwtDirectory.getAbsolutePath());
    }
    // try parse
    try {
        parseJavaInfo("// filler filler filler filler filler", "public class Test extends FlowPanel {",
                "  public Test() {", "  }", "}");
    } finally {
        makeGwtJarsEmpty(gwtDirectory);
    }
}

From source file:de.codecentric.elasticsearch.plugin.kerberosrealm.AbstractUnitTest.java

public final void startES(final Settings settings) throws Exception {
    FileUtils.copyFileToDirectory(getAbsoluteFilePathFromClassPath("roles.yml").toFile(),
            new File("testtmp/config/shield"));

    final Set<Integer> ports = new HashSet<>();
    do {/*from  www  .j  av a  2 s.c  o m*/
        ports.add(NetworkUtil.getServerPort());
    } while (ports.size() < 7);

    final Iterator<Integer> portIt = ports.iterator();

    elasticsearchHttpPort1 = portIt.next();
    elasticsearchHttpPort2 = portIt.next();
    elasticsearchHttpPort3 = portIt.next();

    //elasticsearchNodePort1 = portIt.next();
    //elasticsearchNodePort2 = portIt.next();
    //elasticsearchNodePort3 = portIt.next();

    esNode1 = new PluginEnabledNode(
            getDefaultSettingsBuilder(1, 0, elasticsearchHttpPort1, false, true)
                    .put(settings == null ? Settings.Builder.EMPTY_SETTINGS : settings).build(),
            Lists.newArrayList(ShieldPlugin.class, LicensePlugin.class, KerberosRealmPlugin.class)).start();
    client = esNode1.client();

    esNode2 = new PluginEnabledNode(
            getDefaultSettingsBuilder(2, 0, elasticsearchHttpPort2, true, true)
                    .put(settings == null ? Settings.Builder.EMPTY_SETTINGS : settings).build(),
            Lists.newArrayList(ShieldPlugin.class, LicensePlugin.class, KerberosRealmPlugin.class)).start();

    esNode3 = new PluginEnabledNode(
            getDefaultSettingsBuilder(3, 0, elasticsearchHttpPort3, true, false)
                    .put(settings == null ? Settings.Builder.EMPTY_SETTINGS : settings).build(),
            Lists.newArrayList(ShieldPlugin.class, LicensePlugin.class, KerberosRealmPlugin.class)).start();

    waitForGreenClusterState();
    final NodesInfoResponse nodeInfos = client().admin().cluster().prepareNodesInfo().get();
    final NodeInfo[] nodes = nodeInfos.getNodes();
    Assert.assertEquals(nodes + "", 3, nodes.length);
}