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

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

Introduction

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

Prototype

public static void copyFile(File srcFile, File destFile) throws IOException 

Source Link

Document

Copies a file to a new location preserving the file date.

Usage

From source file:de.awtools.config.PropertyHolderTest.java

@Before
public void setUp() throws IOException {
    userFile = new File(SystemUtils.USER_HOME, "util-user-home-test.properties");
    File propertyFile = new File("src/test/resources/de/awtools/config/copy-to-user-home.properties");
    FileUtils.copyFile(propertyFile, userFile);

    System.setProperty("file1", "aus dem System");
    System.setProperty("Aus_dem_System", "Wert aus dem System");
}

From source file:com.wcs.netbeans.liquiface.ui.wizards.appendchangelog.AppendToChangelogFileWizardAction.java

private void copyFile(File source, File target) {
    try {//from   w  w  w .  ja  va  2  s.c o m
        FileUtils.copyFile(source, target);
    } catch (IOException ex) {
        LOG().log(Level.SEVERE, null, ex);
    }
}

From source file:graphvis.webui.servlets.UploadServlet.java

/**
  * This method receives POST from the index.jsp page and uploads file, 
  * converts into the correct format then places in the HDFS.
  *//*from www.  j a v a  2s .c o  m*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (!isMultipart) {
        response.setStatus(403);
        return;
    }

    File tempDirFileObject = new File(Configuration.tempDirectory);

    // Create/remove temp folder
    if (tempDirFileObject.exists()) {
        FileUtils.deleteDirectory(tempDirFileObject);
    }

    // (Re-)create temp directory
    tempDirFileObject.mkdir();
    FileUtils.copyFile(
            new File(getServletContext()
                    .getRealPath("giraph-1.1.0-SNAPSHOT-for-hadoop-2.2.0-jar-with-dependencies.jar")),
            new File(Configuration.tempDirectory
                    + "/giraph-1.1.0-SNAPSHOT-for-hadoop-2.2.0-jar-with-dependencies.jar"));
    FileUtils.copyFile(new File(getServletContext().getRealPath("dist-graphvis.jar")),
            new File(Configuration.tempDirectory + "/dist-graphvis.jar"));

    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // Sets the size threshold beyond which files are written directly to
    // disk.
    factory.setSizeThreshold(Configuration.MAX_MEMORY_SIZE);

    // Sets the directory used to temporarily store files that are larger
    // than the configured size threshold. We use temporary directory for
    // java
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);

    // Set overall request size constraint
    upload.setSizeMax(Configuration.MAX_REQUEST_SIZE);

    String fileName = "";
    try {
        // Parse the request
        List<?> items = upload.parseRequest(request);
        Iterator<?> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (!item.isFormField()) {
                fileName = new File(item.getName()).getName();
                String filePath = Configuration.tempDirectory + File.separator + fileName;
                File uploadedFile = new File(filePath);
                System.out.println(filePath);
                // saves the file to upload directory
                try {
                    item.write(uploadedFile);
                } catch (Exception ex) {
                    throw new ServletException(ex);
                }
            }
        }

        String fullFilePath = Configuration.tempDirectory + File.separator + fileName;

        String extension = FilenameUtils.getExtension(fullFilePath);

        // Load Files intoHDFS
        // (This is where we do the parsing.)
        loadIntoHDFS(fullFilePath, extension);

        getServletContext().setAttribute("fileName", new File(fullFilePath).getName());
        getServletContext().setAttribute("fileExtension", extension);

        // Displays fileUploaded.jsp page after upload finished
        getServletContext().getRequestDispatcher("/fileUploaded.jsp").forward(request, response);

    } catch (FileUploadException ex) {
        throw new ServletException(ex);
    }

}

From source file:com.ms.commons.test.tool.util.AutoImportProjectTaskUtil.java

@SuppressWarnings({ "unchecked", "deprecation" })
public static Task wrapAutoImportTask(final File project, final Task oldTask) {
    InputStream fis = null;/*from  w  w w.  j a v a  2s.  c  o m*/
    try {
        fis = new BufferedInputStream(project.toURL().openStream());
        SAXBuilder b = new SAXBuilder();
        Document document = b.build(fis);

        List<Element> elements = XPath.selectNodes(document, "/project/build/dependencies/include");

        List<String> addList = new ArrayList<String>(importList);
        if (elements != null) {
            for (Element ele : elements) {
                String uri = ele.getAttribute("uri").getValue().trim().toLowerCase();
                if (importList.contains(uri)) {
                    addList.remove(uri);
                }
            }
        }

        if (addList.size() > 0) {
            System.err.println("Add projects:" + addList);

            List<Element> testElements = XPath.selectNodes(document,
                    "/project/build[@profile='TEST']/dependencies");
            Element testEle;
            if ((testElements == null) || (testElements.size() == 0)) {
                Element buildEle = new Element("build");
                buildEle.setAttribute("profile", "TEST");

                Element filesetsEle = new Element("filesets");
                filesetsEle.setAttribute("name", "java.resdirs");
                Element excludeEle = new Element("exclude");
                excludeEle.setAttribute("fileset", "java.configdir");
                filesetsEle.addContent(excludeEle);

                testEle = new Element("dependencies");

                buildEle.addContent(Arrays.asList(filesetsEle, testEle));

                ((Element) XPath.selectNodes(document, "/project").get(0)).addContent(buildEle);
            } else {
                testEle = testElements.get(0);
            }

            for (String add : addList) {
                Element e = new Element("include");
                e.setAttribute("uri", add);
                testEle.addContent(e);
            }

            String newF = project.getAbsolutePath() + ".new";

            XMLOutputter xmlOutputter = new XMLOutputter();
            Writer writer = new BufferedWriter(new FileWriter(newF));
            xmlOutputter.output(document, writer);
            writer.flush();
            FileUtil.closeCloseAbleQuitly(writer);

            final File newFile = new File(newF);
            return new Task() {

                public void finish() {
                    boolean hasError = false;
                    File backUpFile = new File(project.getAbsoluteFile() + ".backup");
                    try {
                        FileUtils.copyFile(project, backUpFile);
                        FileUtils.copyFile(newFile, project);

                        oldTask.finish();
                    } catch (Exception e) {
                        hasError = true;
                        e.printStackTrace();
                    } finally {
                        try {
                            FileUtils.copyFile(backUpFile, project);
                        } catch (IOException e) {
                            hasError = true;
                            e.printStackTrace();
                        }
                        newFile.delete();
                        backUpFile.delete();
                    }
                    if (hasError) {
                        System.exit(-1);
                    }
                }
            };
        }

        return oldTask;
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        FileUtil.closeCloseAbleQuitly(fis);
    }
}

From source file:hu.bme.mit.trainbenchmark.generator.sql.SqlSerializer.java

@Override
public void initModel() throws IOException {
    // header file (DDL operations)
    final String headerFilePath = gc.getConfigBase().getWorkspaceDir() + SQL_METAMODEL_DIR
            + "railway-header.sql";
    final File headerFile = new File(headerFilePath);

    // destination file
    sqlRawPath = gc.getConfigBase().getModelPathWithoutExtension() + "-raw.sql";
    final File sqlRawFile = new File(sqlRawPath);

    // this overwrites the destination file if it exists
    FileUtils.copyFile(headerFile, sqlRawFile);

    writer = new BufferedWriter(new FileWriter(sqlRawFile, true));
}

From source file:de.uzk.hki.da.format.PublishVideoConversionStrategyTests.java

/**
 * Test.//from   w  w  w  .j  ava  2 s.  c om
 * @throws IOException 
 */
@Test
public void test() throws IOException {

    Document dom = XPathUtils.parseDom(basePath + "premis.xml");
    if (dom == null) {
        throw new RuntimeException("Error while parsing premis.xml");
    }

    Object o = TESTHelper.setUpObject("1", new RelativePath(basePath));
    PublicationRight right = new PublicationRight();
    right.setAudience(Audience.PUBLIC);
    right.setVideoRestriction(new VideoRestriction());
    right.getVideoRestriction().setHeight("360");
    right.getVideoRestriction().setDuration(180);
    o.getRights().getPublicationRights().add(right);

    PublishVideoConversionStrategy s = new PublishVideoConversionStrategy();
    s.setDom(dom);

    ConversionInstruction ci = new ConversionInstruction();
    ci.setSource_file(new DAFile(o.getLatestPackage(), "a", "filename.avi"));
    ci.setTarget_folder("target/");

    s.setObject(o);
    s.setProcessTimeout(250);

    File testFile = new File(basePath + "testfile.txt");
    File pubFile = new File(basePath + "TEST/1/data/dip/public/target/filename.mp4");
    File instFile = new File(basePath + "TEST/1/data/dip/institution/target/filename.mp4");

    FileUtils.copyFile(testFile, pubFile);
    FileUtils.copyFile(testFile, instFile);

    s.convertFile(ci);
}

From source file:com.arhs.mojo.pack200.AbstractMojoTest.java

/**
 * Creates a copy of the original JAR file.
 *
 * @param path          Path to the directory that will contain the copy.
 * @param filename      File name copy./* w w w .  ja  v a2 s. c  om*/
 * @param originalFile  Original file name.
 * @return              Path to File name copied.
 * @throws IOException  If the copy of the original file fails.
 */
protected File copyJar(File path, String filename, String originalFile) throws IOException {
    final File inputJarFileOriginal = new File(originalFile);
    final File inputJarFile = new File(path, filename);

    FileUtils.copyFile(inputJarFileOriginal, inputJarFile);
    return inputJarFile;
}

From source file:com.psaravan.filebrowserview.lib.AsyncTasks.AsyncCopyTask.java

@Override
protected Boolean doInBackground(String... params) {

    if (mCopyInterface != null)
        mCopyInterface.preCopyStartAsync();

    if (mSourceFile == null || mDestDirFile == null) {
        if (mCopyInterface != null)
            mCopyInterface.onCopyCompleteAsync(false);

        return false;
    }//www  .j a  va2  s  .c o m

    if (mSourceFile.isDirectory()) {
        try {
            FileUtils.copyDirectory(mSourceFile, mDestDirFile);
        } catch (Exception e) {
            if (mCopyInterface != null)
                mCopyInterface.onCopyCompleteAsync(false);

            return false;
        }

    } else {
        try {
            FileUtils.copyFile(mSourceFile, mDestDirFile);
        } catch (Exception e) {
            if (mCopyInterface != null)
                mCopyInterface.onCopyCompleteAsync(false);

            return false;
        }

    }

    if (mCopyInterface != null)
        mCopyInterface.onCopyCompleteAsync(true);

    return true;
}

From source file:net.rptools.tokentool.util.FileSaveUtil.java

public static void copyFile(File srcFile, File destDir) {
    try {//from w  ww.  j a  v a 2  s .  c  om
        FileUtils.copyFile(srcFile, new File(destDir, srcFile.getName()));
    } catch (Exception e) {
        log.error("Could not copy " + srcFile, e);
    }
}

From source file:$.MarkdownMojoTest.java

@Test
    public void testInitializationWithFilteredInternalAndExternalFilesUsingRegularExtensions()
            throws MojoExecutionException, IOException {
        MarkdownMojo mojo = new MarkdownMojo();
        mojo.basedir = basedir;/*from   www .ja  v  a  2s  . co m*/
        mojo.buildDirectory = new File(mojo.basedir, "target");
        FileUtils.copyFile(new File("src/test/resources/hello.md"),
                new File(basedir, "src/main/resources/assets/doc/hello.md"));
        // Filtered version:
        FileUtils.copyFile(new File("src/test/resources/hello.md"),
                new File(basedir, "target/classes/assets/doc/hello.md"));
        FileUtils.copyFile(new File("src/test/resources/hello.md"),
                new File(basedir, "src/main/assets/doc/hello.md"));
        // Filtered version:
        FileUtils.copyFile(new File("src/test/resources/hello.md"),
                new File(basedir, "target/wisdom/assets/doc/hello.md"));

        mojo.execute();

        final File internal = new File(mojo.getInternalAssetOutputDirectory(), "doc/hello.html");
        final File external = new File(mojo.getExternalAssetsOutputDirectory(), "doc/hello.html");
        assertThat(internal).isFile();
        assertThat(external).isFile();

        assertThat(FileUtils.readFileToString(internal)).contains("<h1>Hello, " + "Wisdom!</h1>")
                .contains("href=\"http://perdu.com\"");
        assertThat(FileUtils.readFileToString(external)).contains("<h1>Hello, " + "Wisdom!</h1>")
                .contains("href=\"http://perdu.com\"");
    }