Example usage for java.nio.file Files copy

List of usage examples for java.nio.file Files copy

Introduction

In this page you can find the example usage for java.nio.file Files copy.

Prototype

public static long copy(InputStream in, Path target, CopyOption... options) throws IOException 

Source Link

Document

Copies all bytes from an input stream to a file.

Usage

From source file:edu.utah.bmi.ibiomes.lite.IBIOMESLiteManager.java

/**
 * Pull data files (pdb and images) for a given experiment
 * @param fileTreeXmlPath Path to XML file representing the project file tree
 * @param workflowXmlPath Path to XML file representing the experiment workflow
 * @param dataDirPath Path to directory used to store data files
 * @throws SAXException/*w w w.  jav  a2s  .c o  m*/
 * @throws IOException
 * @throws XPathExpressionException 
 * @throws ParserConfigurationException 
 * @throws TransformerException 
 */
private void pullDataFilesForExperiment(String fileTreeXmlPath, String workflowXmlPath, String dataDirPath)
        throws SAXException, IOException, XPathExpressionException, ParserConfigurationException,
        TransformerException {

    if (outputToConsole)
        System.out.println("Copying analysis data files...");

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    Document fileTreeDoc = docBuilder.parse(fileTreeXmlPath);
    fileTreeDoc = Utils.normalizeXmlDoc(fileTreeDoc);

    Element fileTreeRootElt = (Element) fileTreeDoc.getDocumentElement().getChildNodes().item(0);
    String dirPath = fileTreeRootElt.getAttribute("absolutePath");

    XPathReader xreader = new XPathReader(fileTreeDoc);

    //load XML representation of experiment workflow
    Document docWorkflow = docBuilder.parse(workflowXmlPath);
    docWorkflow = Utils.normalizeXmlDoc(docWorkflow);
    Element workflowRootElt = (Element) docWorkflow.getDocumentElement();

    //find main structure for display in Jmol
    Element jmolElt = pullJmolFile(fileTreeDoc, fileTreeRootElt, xreader, dataDirPath, dirPath);
    if (jmolElt != null)
        workflowRootElt.appendChild(docWorkflow.importNode(jmolElt, true));

    //find analysis data
    NodeList matchingFiles = (NodeList) xreader.read("//file[AVUs/AVU[@id='" + FileMetadata.FILE_CLASS
            + "' and text()='" + FileMetadata.FILE_CLASS_ANALYSIS.toUpperCase() + "']]",
            XPathConstants.NODESET);

    //add publication information
    //Element dirNode = (Element)fileTreeDoc.getDocumentElement().getFirstChild();
    //dirNode.setAttribute("publisher", workflowRootElt.getAttribute("publisher"));
    //dirNode.setAttribute("publicationDate", workflowRootElt.getAttribute("publicationDate"));

    //analysis data
    if (matchingFiles != null && matchingFiles.getLength() > 0) {
        Element dataElt = docWorkflow.createElement("analysis");
        workflowRootElt.appendChild(dataElt);

        Element imgElt = docWorkflow.createElement("images");
        Element pdbElt = docWorkflow.createElement("structures");
        Element csvElts = docWorkflow.createElement("spreadsheets");
        Element otherDataElts = docWorkflow.createElement("unknowns");

        dataElt.appendChild(imgElt);
        dataElt.appendChild(csvElts);
        dataElt.appendChild(pdbElt);
        dataElt.appendChild(otherDataElts);

        PlotGenerator plotTool = new PlotGenerator();

        for (int f = 0; f < matchingFiles.getLength(); f++) {
            Element fileNode = (Element) matchingFiles.item(f);
            String dataFilePath = fileNode.getAttribute("absolutePath");
            //copy file
            String dataFileNewName = dataFilePath.substring(dirPath.length() + 1)
                    .replaceAll(PATH_FOLDER_SEPARATOR_REGEX, "_");
            String dataFileDestPath = dataDirPath + PATH_FOLDER_SEPARATOR + dataFileNewName;
            Files.copy(Paths.get(dataFilePath), Paths.get(dataFileDestPath),
                    StandardCopyOption.REPLACE_EXISTING);
            //set read permissions
            if (!Utils.isWindows()) {
                HashSet<PosixFilePermission> permissions = new HashSet<PosixFilePermission>();
                permissions.add(PosixFilePermission.OWNER_READ);
                permissions.add(PosixFilePermission.OWNER_WRITE);
                permissions.add(PosixFilePermission.OWNER_EXECUTE);
                permissions.add(PosixFilePermission.GROUP_READ);
                permissions.add(PosixFilePermission.OTHERS_READ);
                Files.setPosixFilePermissions(Paths.get(dataFileDestPath), permissions);
            }
            //read file AVUs
            NodeList avuNodes = (NodeList) xreader.read("//file[@absolutePath='" + dataFilePath + "']/AVUs/AVU",
                    XPathConstants.NODESET);
            MetadataAVUList avuList = new MetadataAVUList();
            if (avuNodes != null) {
                for (int a = 0; a < avuNodes.getLength(); a++) {
                    Element avuNode = (Element) avuNodes.item(a);
                    avuList.add(new MetadataAVU(avuNode.getAttribute("id").toUpperCase(),
                            avuNode.getFirstChild().getNodeValue()));
                }
            }

            //add reference in XML doc
            String description = avuList.getValue(FileMetadata.FILE_DESCRIPTION);
            String format = fileNode.getAttribute("format");
            if (IBIOMESFileGroup.isJmolFile(format)) {
                Element jmolFileElt = docWorkflow.createElement("structure");
                jmolFileElt.setAttribute("path", dataFileNewName);
                if (description != null && description.length() > 0)
                    jmolFileElt.setAttribute("description", description);
                pdbElt.appendChild(jmolFileElt);
            } else if (format.equals(LocalFile.FORMAT_CSV)) {
                Element csvElt = docWorkflow.createElement("spreadsheet");
                csvElt.setAttribute("path", dataFileNewName);
                if (description != null && description.length() > 0)
                    csvElt.setAttribute("description", description);
                csvElts.appendChild(csvElt);
                //try to generate plot and save image
                try {
                    String imgPath = dataFileNewName + "_plot.png";
                    String plotType = generatePlotForCSV(plotTool, dataFileDestPath, avuList,
                            dataFileDestPath + "_plot", "png");
                    csvElt.setAttribute("plotPath", imgPath);
                    if (outputToConsole) {
                        if (plotType == null)
                            plotType = "";
                        else
                            plotType += " ";
                        System.out.println("\t" + plotType + "plot generated for " + dataFileNewName);
                    }

                } catch (Exception e) {
                    if (outputToConsole)
                        System.out.println(
                                "Warning: Plot for '" + dataFileDestPath + "' could not be generated.");
                    try {
                        if (IBIOMESConfiguration.getInstance().isOutputErrorStackToConsole())
                            e.printStackTrace();
                    } catch (Exception e1) {
                    }
                }
            } else if (IBIOMESFileGroup.isImageFile(format)) {
                Element imgFileElt = docWorkflow.createElement("image");
                imgFileElt.setAttribute("path", dataFileNewName);
                if (description != null && description.length() > 0)
                    imgFileElt.setAttribute("description", description);
                imgElt.appendChild(imgFileElt);
            } else {
                Element otherFileElt = docWorkflow.createElement("unknown");
                otherFileElt.setAttribute("path", dataFileNewName);
                if (description != null && description.length() > 0)
                    otherFileElt.setAttribute("description", description);
                imgElt.appendChild(otherDataElts);
            }
        }
    }

    //update XML files
    File outputXmlAvusFile = new File(fileTreeXmlPath);
    if (outputXmlAvusFile.exists())
        outputXmlAvusFile.delete();

    File outputXmlWorkflowFile = new File(workflowXmlPath);
    if (outputXmlWorkflowFile.exists())
        outputXmlWorkflowFile.delete();

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

    DOMSource source = new DOMSource(fileTreeDoc);
    StreamResult result = null;
    result = new StreamResult(fileTreeXmlPath);
    transformer.transform(source, result);

    source = new DOMSource(docWorkflow);
    result = null;
    result = new StreamResult(outputXmlWorkflowFile);
    transformer.transform(source, result);
}

From source file:com.warfrog.bitmapallthethings.BattEngine.java

private void generateBitmap(String inputName, String outputName) throws Exception {
    System.out.println("Generating " + outputName);

    File input = new File(inputName);
    int size = (int) new FileInputStream(inputName).getChannel().size();

    if (size > getMaxFileSize()) {
        System.err.println(/*from   www. jav a2 s .c  o  m*/
                "ERROR: Skipping " + inputName + " the file size is larger than the maximum size allowed.");
        return;
    }

    int height = (size / (getBytesPerPixel() / 8)) / getWidth();
    int fillerBytes = (size / (getBytesPerPixel() / 8)) % getWidth();

    //encode (repeat this for each file in a directory)
    InputStream header = generateBitmapHeader(getWidth(), height, size, fillerBytes);
    InputStream file = generateFileInputStream(inputName);
    InputStream filler = generateFillerStream(fillerBytes);

    Vector<InputStream> inputStreams = new Vector<InputStream>();
    inputStreams.add(header);
    inputStreams.add(file);
    inputStreams.add(filler);

    SequenceInputStream inputStream = new SequenceInputStream(inputStreams.elements());
    Files.copy(inputStream, new File(outputName).toPath(), StandardCopyOption.REPLACE_EXISTING);
}

From source file:com.maxl.java.aips2sqlite.AllDown.java

public void downEPhaProductsJson(String language, String file_products_json) {
    boolean disp = false;
    ProgressBar pb = new ProgressBar();

    try {// w w w .j  a  va2 s .c  o m
        // Ignore validation for https sites
        setNoValidation();

        // Start timer
        long startTime = System.currentTimeMillis();
        if (disp)
            System.out.print("- Downloading EPha products (" + language + ") file... ");
        else {
            pb.init("- Downloading EPha products (" + language + ") file... ");
            pb.start();
        }

        URL url = null;
        if (language.equals("DE"))
            url = new URL("http://download.epha.ch/cleaned/produkte.json");
        else if (language.equals("FR"))
            url = new URL("http://download.epha.ch/cleaned/produkte.json");
        if (url != null) {
            File destination = new File(file_products_json);

            Files.copy(url.openStream(), destination.toPath(), StandardCopyOption.REPLACE_EXISTING);

            // FileUtils.copyURLToFile(url, destination, 60000, 60000);   
            if (!disp)
                pb.stopp();
            long stopTime = System.currentTimeMillis();
            System.out.println("\r- Downloading EPha products (" + language + ") file... "
                    + destination.length() / 1024 + " kB in " + (stopTime - startTime) / 1000.0f + " sec");
        }
    } catch (Exception e) {
        if (!disp)
            pb.stopp();
        System.err.println(" Exception: in 'downInteractionsCsv'");
        e.printStackTrace();
    }
}

From source file:nl.coinsweb.sdk.FileManager.java

public static void copyAndLinkRdfFile(String internalRef, File source, String contentFileName) {
    if (internalRef == null) {
        throw new CoinsFileManagerException("Registering rdf file in non existing coins container.");
    }// www.ja v a 2  s .  co  m
    Path homePath = getTempZipPath().resolve(internalRef);
    Path rdfPath = homePath.resolve(ONTOLOGIES_PATH);
    Path absoluteTempPath = rdfPath.resolve(contentFileName);

    // check if the folder is empty (it should)
    if (rdfPath.toFile().list().length > 0) {
        throw new CoinsFileManagerException("The FileManager cache already contains an rdf-file.");
    }

    try {
        Files.copy(source.toPath(), absoluteTempPath, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }
}

From source file:dialog.DialogFunctionRoom.java

private void actionAddNoController() {
    String roomName = tfRoomName.getText();
    if (roomName.isEmpty()) {
        JOptionPane.showMessageDialog(null, "Tn phng khng c  trng", "Error",
                JOptionPane.ERROR_MESSAGE);
        tfRoomName.requestFocus();/*from  w w  w  . ja va 2  s .com*/
        return;
    }
    String priceString = tfPrice.getText();
    if (priceString.isEmpty()) {
        JOptionPane.showMessageDialog(null, "Gi phng khng c  trng", "Error",
                JOptionPane.ERROR_MESSAGE);
        tfPrice.requestFocus();
        return;
    }
    double price;
    try {
        price = Double.parseDouble(priceString);
    } catch (NumberFormatException nfe) {
        JOptionPane.showMessageDialog(null, "Gi phng khng ng nh dng", "Error",
                JOptionPane.ERROR_MESSAGE);
        return;
    }
    int max;
    try {
        max = Integer.parseInt(priceString);
    } catch (NumberFormatException nfe) {
        JOptionPane.showMessageDialog(null, "Gi phng khng ng nh dng", "Error",
                JOptionPane.ERROR_MESSAGE);
        return;
    }

    Floor objFloor = (Floor) cbFloor.getSelectedItem();
    int roomType = cbRoomType.getSelectedIndex() + 1;
    ModelPicture modelPicture = new ModelPicture();
    String idRoom = UUID.randomUUID().toString();
    if (!(new ModelRoom()).isExistRoomInFloor(roomName, objFloor.getIdFloor())) {
        mListUriPhotos.stream().forEach((uriPicture) -> {
            File file = new File(uriPicture);
            String fileName = FilenameUtils.getBaseName(file.getName()) + "-" + System.nanoTime() + "."
                    + FilenameUtils.getExtension(file.getName());
            Path source = Paths.get(uriPicture);
            Path destination = Paths.get("files/" + fileName);
            try {
                Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
            } catch (IOException ex) {
                Logger.getLogger(DialogFunctionRoom.class.getName()).log(Level.SEVERE, null, ex);
            }
            Picture objPicture = new Picture(UUID.randomUUID().toString(), idRoom, fileName);
            modelPicture.addItem(objPicture);
            mListPictures.add(objPicture);
        });
        Room objRoom = new Room(idRoom, objFloor.getIdFloor(), roomName, roomType, price,
                Constant.ROOM_CONDITION_AVAILABLE_TYPE, mListPictures, null, objFloor.getFloorName(), max);
        mObjRoom = objRoom;
        if (new ModelRoom().addItem(objRoom)) {
            objFloor.setMaxRoom(objFloor.getMaxRoom() + 1);
            new ModelFloor().editItem(objFloor);
            ImageIcon icon = new ImageIcon(getClass().getResource("/images/ic_success.png").getPath());
            JOptionPane.showMessageDialog(this, "Thm thnh cng!", "Success",
                    JOptionPane.INFORMATION_MESSAGE, icon);
            this.dispose();
        }
    } else {
        JOptionPane.showMessageDialog(this, "Phng  tn ti!", "Error", JOptionPane.ERROR_MESSAGE);
    }
}

From source file:nl.coinsweb.sdk.FileManager.java

public static void copyAndLinkLibrary(String internalRef, File source) {
    if (internalRef == null) {
        throw new CoinsFileManagerException("Registering rdf file in non existing coins container.");
    }/* w w w.j a  v a2 s  .c  o  m*/
    Path homePath = getTempZipPath().resolve(internalRef);
    Path rdfPath = homePath.resolve(ONTOLOGIES_PATH);
    Path absoluteTempPath = rdfPath.resolve(source.getName());

    if (absoluteTempPath.toFile().exists()) {
        log.info("File " + absoluteTempPath.toString() + " already exists, skipping.");
        return;
    }

    try {
        Files.copy(source.toPath(), absoluteTempPath, StandardCopyOption.REPLACE_EXISTING);
        log.info("Copied file " + source.getName() + " to " + internalRef + ".");
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }
}

From source file:de.qucosa.webapi.v1.DocumentResourceFileTest.java

@Test
public void addsMimeTypeElement() throws Exception {
    Path src = new File(this.getClass().getResource("/blank.pdf").toURI()).toPath();
    Path dest = tempFolder.getRoot().toPath().resolve(src.getFileName());
    Files.copy(src, dest, StandardCopyOption.REPLACE_EXISTING);

    mockMvc.perform(post("/document").accept(new MediaType("application", "vnd.slub.qucosa-v1+xml"))
            .contentType(new MediaType("application", "vnd.slub.qucosa-v1+xml"))
            .content("<Opus version=\"2.0\">" + "<Opus_Document>" + "   <DocumentId>815</DocumentId>"
                    + "       <PersonAuthor>" + "           <LastName>Shakespear</LastName>"
                    + "           <FirstName>William</FirstName>" + "       </PersonAuthor>" + "   <TitleMain>"
                    + "       <Value>Macbeth</Value>" + "   </TitleMain>" + "   <IdentifierUrn>"
                    + "       <Value>urn:nbn:foo-4711</Value>" + "   </IdentifierUrn>" + "   <File>"
                    + "       <PathName>1057131155078-6506.pdf</PathName>"
                    + "       <Label>Volltextdokument (PDF)</Label>" + "       <TempFile>blank.pdf</TempFile>"
                    + "       <OaiExport>1</OaiExport>" + "       <FrontdoorVisible>1</FrontdoorVisible>"
                    + "   </File>" + "</Opus_Document>" + "</Opus>"))
            .andExpect(status().isCreated());

    ArgumentCaptor<InputStream> argCapt = ArgumentCaptor.forClass(InputStream.class);
    verify(fedoraRepository).modifyDatastreamContent(eq("qucosa:815"), eq("QUCOSA-XML"), anyString(),
            argCapt.capture());/*w w w .j av a  2 s  . com*/
    Document control = XMLUnit.buildControlDocument(new InputSource(argCapt.getValue()));

    assertXpathExists("/Opus/Opus_Document/File[MimeType='application/pdf']", control);
}

From source file:org.pentaho.marketplace.domain.services.BaPluginService.java

private void writeResourceToFolder(URL resourceUrl, Path destinationFolder) {
    try {/*  w w  w .  j a v a 2 s.  c o  m*/
        InputStream inputStream = resourceUrl.openConnection().getInputStream();
        String fileName = FilenameUtils.getName(resourceUrl.toString());
        Path destinationFile = destinationFolder.resolve(fileName);
        Files.copy(inputStream, destinationFile, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        this.getLogger().error(
                "Error copying " + resourceUrl.toString() + " to destination folder " + destinationFolder, e);
    }
}

From source file:org.apache.drill.yarn.scripts.ScriptUtils.java

public void copyFile(File source, File dest) throws IOException {
    Files.copy(source.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING);
}

From source file:de.qucosa.webapi.v1.DocumentResourceFileTest.java

@Test
public void addsFileSize() throws Exception {
    Path src = new File(this.getClass().getResource("/blank.pdf").toURI()).toPath();
    Path dest = tempFolder.getRoot().toPath().resolve(src.getFileName());
    Files.copy(src, dest, StandardCopyOption.REPLACE_EXISTING);

    mockMvc.perform(post("/document").accept(new MediaType("application", "vnd.slub.qucosa-v1+xml"))
            .contentType(new MediaType("application", "vnd.slub.qucosa-v1+xml"))
            .content("<Opus version=\"2.0\">" + "<Opus_Document>" + "   <DocumentId>815</DocumentId>"
                    + "       <PersonAuthor>" + "           <LastName>Shakespear</LastName>"
                    + "           <FirstName>William</FirstName>" + "       </PersonAuthor>" + "   <TitleMain>"
                    + "       <Value>Macbeth</Value>" + "   </TitleMain>" + "   <IdentifierUrn>"
                    + "       <Value>urn:nbn:foo-4711</Value>" + "   </IdentifierUrn>" + "   <File>"
                    + "       <PathName>1057131155078-6506.pdf</PathName>"
                    + "       <Label>Volltextdokument (PDF)</Label>" + "       <TempFile>blank.pdf</TempFile>"
                    + "       <OaiExport>1</OaiExport>" + "       <FrontdoorVisible>1</FrontdoorVisible>"
                    + "   </File>" + "</Opus_Document>" + "</Opus>"))
            .andExpect(status().isCreated());

    ArgumentCaptor<InputStream> argCapt = ArgumentCaptor.forClass(InputStream.class);
    verify(fedoraRepository).modifyDatastreamContent(eq("qucosa:815"), eq("QUCOSA-XML"), anyString(),
            argCapt.capture());/*from   w  w  w .  java2s .  co m*/
    Document control = XMLUnit.buildControlDocument(new InputSource(argCapt.getValue()));

    assertXpathExists("/Opus/Opus_Document/File[FileSize='11112']", control);
}