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:com.orange.ocara.model.export.docx.AuditDocxExporter.java

private void copyAuditComment(Comment comment, File commentDir) throws IOException, Ole10NativeException {
    switch (comment.getType()) {
    case PHOTO:/*from  ww w.  j  ava2  s.  com*/
        FileUtils.copyFileToDirectory(FileUtils.toFile(new URL(comment.getAttachment())), commentDir);
        break;

    case AUDIO: {

        String baseName = FilenameUtils.getBaseName(comment.getAttachment());

        File from = FileUtils.toFile(new URL(comment.getAttachment()));
        File to = new File(commentDir, String.format("%s.bin", baseName));

        createOleObject(from, to);
        break;
    }

    default:
        break;
    }
}

From source file:com.dianping.maven.plugin.tools.wms.WorkspaceManagementServiceImpl.java

private void generateContainerProject(WorkspaceContext context) throws WorkspaceManagementException {
    File projectBase = new File(context.getBaseDir(), "phoenix-container");
    File sourceFolder = new File(projectBase, "src/main/java");
    File resourceFolder = new File(projectBase, "src/main/resources");
    File webinfFolder = new File(projectBase, "src/main/webapp/WEB-INF");
    try {//from  ww  w .j av  a 2 s  .co m
        FileUtils.forceMkdir(sourceFolder);
        FileUtils.forceMkdir(resourceFolder);
        FileUtils.forceMkdir(webinfFolder);

        FileUtils.copyFileToDirectory(FileUtils.toFile(this.getClass().getResource("/byteman-2.1.2.jar")),
                resourceFolder);

        // web.xml
        ContainerWebXMLGenerator containerWebXMLGenerator = new ContainerWebXMLGenerator();
        containerWebXMLGenerator.generate(new File(webinfFolder, "web.xml"), null);

        // pom.xml
        ContainerPomXMLGenerator containerPomXMLGenerator = new ContainerPomXMLGenerator();
        Map<String, String> containerPomXMLGeneratorContext = new HashMap<String, String>();
        containerPomXMLGeneratorContext.put("phoenixRouterVersion", context.getPhoenixRouterVersion());
        containerPomXMLGenerator.generate(new File(projectBase, "pom.xml"), containerPomXMLGeneratorContext);

        // BizServer.java
        ContainerBizServerGenerator containerBizServerGenerator = new ContainerBizServerGenerator();
        containerBizServerGenerator
                .generate(new File(sourceFolder, "com/dianping/phoenix/container/BizServer.java"), null);

        context.setBootstrapProjectDir(projectBase);
    } catch (Exception e) {
        throw new WorkspaceManagementException(e);
    }
}

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

@Override
public List<Event> convertFile(ConversionInstruction ci) throws IOException {

    if (ci.getConversion_routine() == null)
        throw new IllegalStateException("conversionRoutine not set");
    if (ci.getConversion_routine().getTarget_suffix().isEmpty())
        throw new IllegalStateException("target suffix in conversionRoutine not set");

    List<Event> results = new ArrayList<Event>();

    String input = ci.getSource_file().toRegularFile().getAbsolutePath();

    for (String audience : audiences) {

        String audience_lc = audience.toLowerCase();

        DAFile target = new DAFile(object.getLatestPackage(), pips + "/" + audience_lc,
                Utilities.slashize(ci.getTarget_folder()) + FilenameUtils.getBaseName(input) + "."
                        + ci.getConversion_routine().getTarget_suffix());
        target.toRegularFile().getParentFile().mkdirs();

        String numberOfPagesText = null;
        if (getPublicationRightForAudience(audience) != null)
            if (getPublicationRightForAudience(audience).getTextRestriction() != null)
                if (getPublicationRightForAudience(audience).getTextRestriction().getPages() != null)
                    numberOfPagesText = getPublicationRightForAudience(audience).getTextRestriction().getPages()
                            .toString();

        String certainPagesText = null;
        if (getPublicationRightForAudience(audience) != null) {
            certainPagesText = "";
            if (getPublicationRightForAudience(audience).getTextRestriction() != null)
                if (getPublicationRightForAudience(audience).getTextRestriction().getCertainPages() != null)
                    for (int i = 0; i < getPublicationRightForAudience(audience).getTextRestriction()
                            .getCertainPages().length; i++) {
                        if (!certainPagesText.equals(""))
                            certainPagesText += " ";
                        certainPagesText += getPublicationRightForAudience(audience).getTextRestriction()
                                .getCertainPages()[i];
                    }/*w w w  .  j ava2  s .  com*/
            logger.debug("reduce to certain pages: " + certainPagesText);

        }

        // copy whole file if no restrictions are found
        if (numberOfPagesText == null && certainPagesText == null) {
            try {
                FileUtils.copyFileToDirectory(new File(input), target.toRegularFile().getParentFile());
                Event e = new Event();
                e.setDetail("Copied PDF");
                e.setSource_file(ci.getSource_file());
                e.setTarget_file(target);
                e.setType("CONVERT");
                e.setDate(new Date());
                results.add(e);
            } catch (IOException e) {
                throw new RuntimeException("Could not copy PDF!", e);
            }
            continue;
        }
        PdfService pdf = new PdfService(new File(input), target.toRegularFile());
        pdf.reduceToCertainPages(numberOfPagesText, certainPagesText);
        Event e = new Event();
        e.setDetail("converted with PDFBox");
        e.setSource_file(ci.getSource_file());
        e.setTarget_file(target);
        e.setType("CONVERT");
        e.setDate(new Date());
        results.add(e);

    }

    return results;

}

From source file:eu.annocultor.utils.OntologySubtractor.java

private static void copyRdfFiles(File sourceDir, File destinationDir) throws IOException {
    File[] allRdfFiles = sourceDir.listFiles(new FilenameFilter() {

        @Override/*from   w w w .  j  av  a2s  . c om*/
        public boolean accept(File dir, String name) {
            return name.endsWith(".rdf") && !name.endsWith(DELETED_RDF);
        }
    });

    for (File file : allRdfFiles) {
        FileUtils.copyFileToDirectory(file, destinationDir);
    }
}

From source file:com.stam.batchmove.BatchMoveUtils.java

public static void showFilesFrame(Object[][] data, String[] columnNames, final JFrame callerFrame) {
    final FilesFrame filesFrame = new FilesFrame();

    DefaultTableModel model = new DefaultTableModel(data, columnNames) {

        private static final long serialVersionUID = 1L;

        @Override/*from   w w  w  .ja v a  2  s . c  om*/
        public Class<?> getColumnClass(int column) {
            return getValueAt(0, column).getClass();
        }

        @Override
        public boolean isCellEditable(int row, int column) {
            return column == 0;
        }
    };
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setHorizontalAlignment(JLabel.CENTER);
    final JTable table = new JTable(model);
    for (int i = 1; i < table.getColumnCount(); i++) {
        table.setDefaultRenderer(table.getColumnClass(i), renderer);
    }
    //            table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    table.setRowHeight(30);
    table.getTableHeader().setFont(new Font("Serif", Font.BOLD, 14));
    table.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
    table.setRowSelectionAllowed(false);
    table.getColumnModel().getColumn(0).setMaxWidth(35);
    table.getColumnModel().getColumn(1).setPreferredWidth(350);
    table.getColumnModel().getColumn(2).setPreferredWidth(90);
    table.getColumnModel().getColumn(2).setMaxWidth(140);
    table.getColumnModel().getColumn(3).setMaxWidth(90);

    JPanel tblPanel = new JPanel();
    JPanel btnPanel = new JPanel();

    tblPanel.setLayout(new BorderLayout());
    if (table.getRowCount() > 15) {
        JScrollPane scrollPane = new JScrollPane(table);
        tblPanel.add(scrollPane, BorderLayout.CENTER);
    } else {
        tblPanel.add(table.getTableHeader(), BorderLayout.NORTH);
        tblPanel.add(table, BorderLayout.CENTER);
    }

    btnPanel.setLayout(new FlowLayout(FlowLayout.LEFT));

    filesFrame.setMinimumSize(new Dimension(800, 600));
    filesFrame.setLayout(new BorderLayout());
    filesFrame.add(tblPanel, BorderLayout.NORTH);
    filesFrame.add(btnPanel, BorderLayout.SOUTH);

    final JLabel resultsLabel = new JLabel();

    JButton cancelBtn = new JButton("Cancel");
    cancelBtn.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            filesFrame.setVisible(false);
            callerFrame.setVisible(true);
        }
    });

    JButton moveBtn = new JButton("Copy");
    moveBtn.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            fileChooser.setDialogTitle("Choose target directory");
            int selVal = fileChooser.showOpenDialog(null);
            if (selVal == JFileChooser.APPROVE_OPTION) {
                File selection = fileChooser.getSelectedFile();
                String targetPath = selection.getAbsolutePath();

                DefaultTableModel dtm = (DefaultTableModel) table.getModel();
                int nRow = dtm.getRowCount();
                int copied = 0;
                for (int i = 0; i < nRow; i++) {
                    Boolean selected = (Boolean) dtm.getValueAt(i, 0);
                    String filePath = dtm.getValueAt(i, 1).toString();

                    if (selected) {
                        try {
                            FileUtils.copyFileToDirectory(new File(filePath), new File(targetPath));
                            dtm.setValueAt("Copied", i, 3);
                            copied++;
                        } catch (Exception ex) {
                            Logger.getLogger(SelectionFrame.class.getName()).log(Level.SEVERE, null, ex);
                            dtm.setValueAt("Failed", i, 3);
                        }
                    }
                }
                resultsLabel.setText(copied + " files copied. Finished!");
            }
        }
    });
    btnPanel.add(cancelBtn);
    btnPanel.add(moveBtn);
    btnPanel.add(resultsLabel);

    filesFrame.revalidate();
    filesFrame.setVisible(true);

    callerFrame.setVisible(false);
}

From source file:com.zotoh.maedr.etc.CmdSamples.java

protected void eval(String[] args) throws Exception {
    if (args == null || args.length < 1 || !"samples".equals(args[1]) || !"demo".equals(args[0])) {
        throw new CmdHelpError();
    }/*from  ww w  . j av  a2 s  .  co  m*/
    Module<?, ?> mod = Module.getPipelineModule();
    String shortmn = mod.getShortName();
    String mn = mod.getName();
    String lang = args.length > 2 ? args[2] : "java";
    File a, sample = new File("sample_apps");
    sample.mkdirs();
    String ptr, ms;
    Properties ps;
    File demo_src = new File(getMaedrDir(), "samples");
    File tp;
    String appprops = rc2Str("com/zotoh/maedr/env/" + APPPROPS, "utf-8");

    System.out.println("\n\n");
    System.out.println("Creating samples pack...");
    System.out.println("\n");

    for (int i = 0; i < SPLDIRS.length; ++i) {

        ps = new Properties();
        ps.put("apptype", APPTYPE_SVR);
        ps.put("storage", false);
        ptr = SPLDIRS[i];

        System.out.format("%-24s%s\n", "Creating sample: ", ptr);

        a = create0(true, sample, ptr);
        ms = readFile(new File(new File(demo_src, ptr), "app.mf"), "utf-8");
        ms = strstr(ms, "${PIPELINE}", shortmn);
        ms = strstr(ms, "${PREAMBLE}", "scala".equals(lang) ? "Preamble" : "$Preamble");
        if ("stateful".equals(ptr)) {
            ps.put("storage", true);
        } else if ("ssl".equals(ptr)) {
            tp = new File(new File(a, CFG), "test.p12");
            ms = strstr(ms, "$KEY.P12", (isWindows() ? "file:/" : "file:") + niceFPath(tp));
        } else if ("file".equals(ptr)) {
            tp = new File(new File(a, TMP), "infiles");
            tp.mkdirs();
            ms = strstr(ms, "$FILEPICK_SRC", niceFPath(tp));
            tp = new File(new File(a, TMP), "cache");
            tp.mkdirs();
            ms = strstr(ms, "$FILEPICK_DES", niceFPath(tp));
        } else if ("websock".equals(ptr)) {
            FileUtils.copyFileToDirectory(new File(new File(demo_src, ptr), "squarenum.html"),
                    new File(a, CFG));
            FileUtils.copyFileToDirectory(new File(new File(demo_src, ptr), "jquery.js"), new File(a, CFG));
        } else if ("jetty".equals(ptr) || "web".equals(ptr)) {
            ps.put("apptype", APPTYPE_WEB);
            String bs = "assets";
            File ss = new File(a, "webapps/scripts");
            ss.mkdirs();
            File ii = new File(a, "webapps/images");
            ii.mkdirs();
            File cc = new File(a, "webapps/styles");
            cc.mkdirs();
            FileUtils.copyFileToDirectory(new File(new File(demo_src, bs), "favicon.ico"), ii);
            FileUtils.copyFileToDirectory(new File(new File(demo_src, bs), "test.js"), ss);
            FileUtils.copyFileToDirectory(new File(new File(demo_src, bs), "main.css"), cc);
            if ("web".equals(ptr)) {
                File inf = new File(a, "webapps/WEB-INF");
                inf.mkdirs();
                new File(a, "webapps/WEB-INF/classes").mkdirs();
                FileUtils.copyFileToDirectory(new File(new File(demo_src, ptr), "web.xml"), inf);
            }
            ms = strstr(ms, "$RESBASE", new File(a, "webapps").toURI().toURL().toExternalForm());
        } else if ("pop3".equals(ptr)) {
            appprops = "maedr.pop3.mockstore=com.zotoh.maedr.mock.mail.MockPop3Store\n" + appprops;
        }

        create1(a, ms, ps);

        ps.put("package", "demo." + ptr);
        ps.put("delegate", "");
        if ("delegate".equals(ptr)) {
            ps.put("delegate", mn + "Delegate");
        }
        ps.put("lang", lang);

        create2(a, appprops, ps);
        create3s(a, demo_src, ptr, ps);
        create4(a, ps);
        create5(a, ps);
        create6(a);
        create8(a, ps);
    }

    System.out.println("");
    System.out.println("All samples created successfully.");
    System.out.println("");

}

From source file:dao.EntryDaoTest.java

@Before
public void setUp() {
    String fSeparator = File.separator;
    try {//from w  ww.  j a v  a  2  s .  co  m
        File folder = new File(
                System.getProperty("user.dir") + fSeparator + "MyDiaryBook" + fSeparator + "Users" + fSeparator
                        + "Panagiwtis Georgiadis" + fSeparator + "Entries" + fSeparator + "PAOK");
        folder.mkdirs();

        File textFolder = new File(folder.toString() + fSeparator + "Texts");
        textFolder.mkdirs();
        File textFile = new File(textFolder.toString() + fSeparator + "test.txt");

        FileWriter fw = null;
        BufferedWriter bw = null;
        fw = new FileWriter(textFile, true);
        bw = new BufferedWriter(fw);
        bw.write("test0123456789");
        if (bw != null)
            bw.close();
        fw.close();
        File imageFolder = new File(folder.toString() + fSeparator + "Images");
        imageFolder.mkdirs();
        String imageSourcePath = System.getProperty("user.dir") + fSeparator + "src" + fSeparator + "test"
                + fSeparator + "java" + fSeparator + "resources" + fSeparator + "testImg.jpg";
        File imageSourceFile = new File(imageSourcePath);
        FileUtils.copyFileToDirectory(imageSourceFile, imageFolder);

        String videoSourcePath = System.getProperty("user.dir") + fSeparator + "src" + fSeparator + "test"
                + fSeparator + "java" + fSeparator + "resources" + fSeparator + "testVideo.mp4";
        File videoSourceFile = new File(videoSourcePath);
        File videoFolder = new File(folder.toString() + fSeparator + "Videos");
        videoFolder.mkdirs();
        FileUtils.copyFileToDirectory(videoSourceFile, videoFolder);
    } catch (IOException ex) {
        Logger.getLogger(EntryDaoTest.class.getName()).log(Level.SEVERE, null, ex);
    }
    Login.username = "Panagiwtis Georgiadis";
}

From source file:ch.bender.evacuate.RunnerTest.java

/**
 * This method is executed just before each test method
 * /*from w  w  w . ja v a  2  s.  c om*/
 * @throws Throwable
 *         On any problem (test method will not be executed)
 */
@Before
public void setUp() throws Throwable {
    myLog.debug("entering");
    try {
        if (Files.exists(Testconstants.ROOT_DIR)) {
            Helper.deleteDirRecursive(Testconstants.ROOT_DIR);
        }

        /*
         * Preparing the test sandbox in current directory:
         * 
         * testsandbox
         *   +- orig
         *      +- sub1
         *         +- fileSub12.txt
         *   +- backup
         *      +- sub1
         *         +- fileSub1.txt
         *         +- fileSub12.txt
         *      +- sub2
         *         +- sub2sub1
         *            +- fileSub2Sub1.txt
         *         +- fileSub2.txt
         *      +- file1.txt
         *   +- evacuate
         *       <empty>
         */
        Files.createDirectory(Testconstants.ROOT_DIR);

        myOrigDir = Testconstants.createNewFolder(Testconstants.ROOT_DIR, "orig");
        myOrigDirSub1 = Testconstants.createNewFolder(myOrigDir, "sub1");
        myOrigDirSub2 = Testconstants.createNewFolder(myOrigDir, "sub2");
        myOrigDirSub2Sub1 = Testconstants.createNewFolder(myOrigDirSub2, "sub2sub1");

        myOrigFile1 = Testconstants.createNewFile(myOrigDir, "file1.txt");
        myOrigFileSub1 = Testconstants.createNewFile(myOrigDirSub1, "fileSub1.txt");
        myOrigFileSub12 = Testconstants.createNewFile(myOrigDirSub1, "fileSub12.txt");
        myOrigFileSub2 = Testconstants.createNewFile(myOrigDirSub2, "fileSub2.txt");
        myOrigFileSub2Sub1 = Testconstants.createNewFile(myOrigDirSub2Sub1, "fileSub2Sub1.txt");

        myBackupDir = Testconstants.createNewFolder(Testconstants.ROOT_DIR, "backup");
        FileUtils.copyFileToDirectory(myOrigFile1.toFile(), myBackupDir.toFile());
        FileUtils.copyDirectoryToDirectory(myOrigDirSub1.toFile(), myBackupDir.toFile());
        FileUtils.copyDirectoryToDirectory(myOrigDirSub2.toFile(), myBackupDir.toFile());

        myEvacuateDir = Testconstants.createNewFolder(Testconstants.ROOT_DIR, "evacuate");

        // delete some objects from orig dir:
        Helper.deleteDirRecursive(myOrigDirSub2);
        Files.delete(myOrigFile1);
        Files.delete(myOrigFileSub1);

        myDryRun = false;
        myMove = false;
        myOrigDirStr = myOrigDir.toString();
        myBackupDirStr = myBackupDir.toString();
        myEvacuateDirStr = myEvacuateDir.toString();

    } catch (Throwable t) {
        myLog.error("Throwable caught in setup", t);
        throw t;
    }
}

From source file:com.pieframework.runtime.utils.ArtifactManager.java

private void copy(String download, String filter, String localPath, String virtualPath) {

    /*System.out.println("download:"+download+
             "\nfilter:"+filter+/*from  ww  w.  ja va2 s. co  m*/
             "\nlocalPath:"+localPath+
             "\nvirtualPath:"+virtualPath);
    */
    boolean match = true;
    if (!StringUtils.empty(filter)) {
        match = FilenameUtils.wildcardMatch(FilenameUtils.separatorsToSystem(download), filter);
    }

    if (match) {

        File destinationVirtualFile = new File(FilenameUtils.separatorsToSystem(virtualPath));
        File destination = new File(localPath + destinationVirtualFile.getParent());
        destination.mkdirs();

        if (destination.exists()) {
            File downloadFile = new File(download);
            try {
                FileUtils.copyFileToDirectory(downloadFile, destination);
                File copiedFile = new File(
                        destination.getPath() + File.separatorChar + destinationVirtualFile.getName());
                if (copiedFile.exists()) {
                    System.out.println(
                            "file copied:" + copiedFile + " crc:" + FileUtils.checksumCRC32(copiedFile));
                } else {
                    //TODO error
                }

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {
            //TODO error
        }

    }
}

From source file:ml.shifu.shifu.core.processor.ManageModelProcessor.java

/**
 * switch to different model/* ww w  .  j av a 2s. c  o m*/
 *
 * @param modelName
 * @throws IOException
 */
private void switchModel(String modelName) throws IOException {
    //get current branch
    String currentModelName = null;
    try {
        currentModelName = getCurrentModelName();
    } catch (IOException e) {
        log.info("Could not get the current model name");
        currentModelName = "master";
    }

    //log.info("The current model will backup to {} folder", currentModelName);

    //first, backup to currentModelName
    saveModel(currentModelName);

    //is it new ?
    File thisModel = new File(Constants.BACKUPNAME + File.separator + modelName);
    if (!thisModel.exists()) {
        //no exist

    } else {
        //exist
        //copy files
        File modelFile = new File(String.format("%s/%s/ModelConfig.json", Constants.BACKUPNAME, modelName));
        File columnFile = new File(String.format("%s/%s/ModelConfig.json", Constants.BACKUPNAME, modelName));
        File workspace = new File("./");

        try {
            FileUtils.copyFileToDirectory(modelFile, workspace);
            if (columnFile.exists()) {
                FileUtils.copyFileToDirectory(columnFile, workspace);
            }
        } catch (IOException e) {
            //TODO
            e.printStackTrace();
        }

        //copy models
        File sourceModelFolder = new File(String.format("./%s/%s/models/", Constants.BACKUPNAME, modelName));
        File workspaceFolder = new File("./models");
        if (sourceModelFolder.isDirectory()) {
            File[] files = sourceModelFolder.listFiles(new FileFilter() {
                @Override
                public boolean accept(File file) {
                    return file.isFile() && file.getName().startsWith("model");
                }
            });

            if (files != null) {
                for (File model : files) {
                    try {
                        FileUtils.copyFileToDirectory(model, workspaceFolder);
                    } catch (IOException e) {
                        log.info("Fail to copy models file");
                    }
                }
            } else {
                throw new IOException(
                        String.format("Failed to list files in %s", sourceModelFolder.getAbsolutePath()));
            }
        } else {
            log.error("{} does not exist or is not a directory!", sourceModelFolder.getAbsoluteFile());
        }

    }

    File file = new File("./.HEAD");
    BufferedWriter writer = null;
    try {
        FileUtils.forceDelete(file);
        writer = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(file), Constants.DEFAULT_CHARSET));
        writer.write(modelName);
    } catch (IOException e) {
        log.info("Fail to rewrite HEAD file");
    } finally {
        if (writer != null) {
            writer.close();
        }
    }

    log.info("Switch model: {} successfully", modelName);
}