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:msearch.io.MSFilmlisteLesen.java

private boolean filmlisteEntpackenKopieren(File vonDatei, File nachDatei) {
    boolean ret = false;
    String vonDateiName = vonDatei.getName();
    BufferedInputStream in;/*from  w  w w  . j  a v a2s  .c om*/
    if (vonDateiName.equals(nachDatei.getName())) {
        return true;
    }
    try {
        if (vonDatei.getName().endsWith(MSConst.FORMAT_XZ)) {
            in = new BufferedInputStream(new XZInputStream(new FileInputStream(vonDatei)));
        } else if (vonDateiName.endsWith(MSConst.FORMAT_BZ2)) {
            in = new BufferedInputStream(new BZip2CompressorInputStream(new FileInputStream(vonDatei)));
        } else if (vonDateiName.endsWith(MSConst.FORMAT_ZIP)) {
            ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(vonDatei));
            zipInputStream.getNextEntry();
            in = new BufferedInputStream(zipInputStream);
        } else {
            Files.copy(Paths.get(vonDatei.getPath()), Paths.get(nachDatei.getPath()),
                    StandardCopyOption.REPLACE_EXISTING);
            return true;
            //in = new BufferedInputStream(new FileInputStream(vonDatei));
        }
        FileOutputStream fOut;
        byte[] buffer = new byte[1024];
        int n = 0;
        int count = 0;
        int countMax;
        if (vonDateiName.endsWith(MSConst.FORMAT_XZ) || vonDateiName.endsWith(MSConst.FORMAT_BZ2)
                || vonDateiName.endsWith(MSConst.FORMAT_ZIP)) {
            countMax = 44;
        } else {
            countMax = 250;
        }
        fOut = new FileOutputStream(nachDatei);
        this.notifyProgress(vonDateiName);
        while (!MSConfig.getStop() && (n = in.read(buffer)) != -1) {
            fOut.write(buffer, 0, n);
            ++count;
            if (count > countMax) {
                this.notifyProgress(vonDateiName);
                count = 0;
            }
        }
        if (MSConfig.getStop()) {
            ret = false;
        } else {
            ret = true;
        }
        try {
            fOut.close();
            in.close();
        } catch (Exception e) {
        }
    } catch (Exception ex) {
        MSLog.fehlerMeldung(915236765, MSLog.FEHLER_ART_PROG,
                "MSearchIoXmlFilmlisteLesen.filmlisteEntpackenKopieren", ex);
    }
    return ret;
}

From source file:com.evolveum.midpoint.init.InitialDataImport.java

private File[] getInitialImportObjects() {
    URL path = InitialDataImport.class.getClassLoader().getResource("initial-objects");
    String resourceType = path.getProtocol();

    File[] files = null;/*from  w  w w . ja v a 2s  . com*/
    File folder = null;

    if ("zip".equals(resourceType) || "jar".equals(resourceType)) {
        try {
            File tmpDir = new File(configuration.getMidpointHome() + "/tmp");
            if (!tmpDir.mkdir()) {
                LOGGER.warn(
                        "Failed to create temporary directory for inital objects {}. Maybe it already exists",
                        configuration.getMidpointHome() + "/tmp");
            }

            tmpDir = new File(configuration.getMidpointHome() + "/tmp/initial-objects");
            if (!tmpDir.mkdir()) {
                LOGGER.warn(
                        "Failed to create temporary directory for inital objects {}. Maybe it already exists",
                        configuration.getMidpointHome() + "/tmp/initial-objects");
            }

            //prerequisite: we are expecting that the files are store in the same archive as the source code that is loading it
            URI src = InitialDataImport.class.getProtectionDomain().getCodeSource().getLocation().toURI();
            LOGGER.trace("InitialDataImport code location: {}", src);
            Map<String, String> env = new HashMap<>();
            env.put("create", "false");
            URI normalizedSrc = new URI(src.toString().replaceFirst("file:", "jar:file:"));
            LOGGER.trace("InitialDataImport normalized code location: {}", normalizedSrc);
            try (FileSystem zipfs = FileSystems.newFileSystem(normalizedSrc, env)) {
                Path pathInZipfile = zipfs.getPath("/initial-objects");
                //TODO: use some well defined directory, e.g. midPoint home
                final Path destDir = Paths.get(configuration.getMidpointHome() + "/tmp");
                Files.walkFileTree(pathInZipfile, new SimpleFileVisitor<Path>() {
                    @Override
                    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                        final Path destFile = Paths.get(destDir.toString(), file.toString());
                        LOGGER.trace("Extracting file {} to {}", file, destFile);
                        Files.copy(file, destFile, StandardCopyOption.REPLACE_EXISTING);
                        return FileVisitResult.CONTINUE;
                    }

                    @Override
                    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                            throws IOException {
                        final Path dirToCreate = Paths.get(destDir.toString(), dir.toString());
                        if (Files.notExists(dirToCreate)) {
                            LOGGER.trace("Creating directory {}", dirToCreate);
                            Files.createDirectory(dirToCreate);
                        }
                        return FileVisitResult.CONTINUE;
                    }
                });

            }
            folder = new File(configuration.getMidpointHome() + "/tmp/initial-objects");
        } catch (IOException ex) {
            throw new RuntimeException(
                    "Failed to copy initial objects file out of the archive to the temporary directory", ex);
        } catch (URISyntaxException ex) {
            throw new RuntimeException("Failed get URI for the source code bundled with initial objects", ex);
        }
    }

    if ("file".equals(resourceType)) {
        folder = getResource("initial-objects");
    }

    files = folder.listFiles(new FileFilter() {

        @Override
        public boolean accept(File pathname) {
            if (pathname.isDirectory()) {
                return false;
            }

            return true;
        }
    });
    Arrays.sort(files, new Comparator<File>() {

        @Override
        public int compare(File o1, File o2) {
            int n1 = getNumberFromName(o1);
            int n2 = getNumberFromName(o2);

            return n1 - n2;
        }
    });

    return files;
}

From source file:io.fabric8.docker.client.impl.BuildImage.java

@Override
public OutputHandle fromTar(InputStream is) {
    try {/*  ww w .  java 2  s. co m*/
        File tempFile = Files.createTempFile(Paths.get(DEFAULT_TEMP_DIR), DOCKER_PREFIX, BZIP2_SUFFIX).toFile();
        Files.copy(is, tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        return fromTar(tempFile.getAbsolutePath());
    } catch (Exception e) {
        throw DockerClientException.launderThrowable(e);
    }
}

From source file:com.eqbridges.vertx.VerticleModuleMojo.java

@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
    Path to = toPath.resolve(fromPath.relativize(file));
    Files.copy(file, to, copyOption);
    log.info(format("Copied file [%s] -> [%s]", file.getFileName(), to.normalize()));
    return FileVisitResult.CONTINUE;
}

From source file:at.ac.tuwien.ims.latex2mobiformulaconv.converter.Converter.java

/**
 * This will save the HTML markup + css file to a specified folder
 *
 * @param tempFilepath the temp folder where
 * @return//from w  ww.  j av  a 2  s  . c o m
 */
private Path exportMarkup(Path tempFilepath) {
    Path resultPath;
    if (outputPath != null) {
        resultPath = outputPath;
    } else {
        resultPath = workingDirectory;
    }

    Path markupDir = resultPath.resolve(title + "-markup");
    try {
        try {
            Files.createDirectory(markupDir);
        } catch (FileAlreadyExistsException e) {
            // do nothing
        }

        Path tempDirPath = tempFilepath.getParent();
        File tempDir = tempDirPath.toFile();

        // Copy all files from temp folder to the markup output folder
        String[] files = tempDir.list(FileFileFilter.FILE);
        for (int i = 0; i < files.length; i++) {
            Files.copy(tempDirPath.resolve(files[i]), markupDir.resolve(files[i]),
                    StandardCopyOption.REPLACE_EXISTING);
        }

        logger.info("Exported markup to folder: " + markupDir.toAbsolutePath().toString());
    } catch (IOException e) {
        logger.error("Error saving markup files: " + e.getMessage(), e);
        return null;
    }
    return markupDir;
}

From source file:com.esp8266.mkspiffs.ESP8266FS.java

private void createAndUpload() {
    if (!PreferencesData.get("target_platform").contentEquals("esp8266")) {
        System.err.println();//from   w  w  w .  j  a v  a 2  s . c om
        editor.statusError("SPIFFS Not Supported on " + PreferencesData.get("target_platform"));
        return;
    }

    if (!BaseNoGui.getBoardPreferences().containsKey("build.spiffs_start")
            || !BaseNoGui.getBoardPreferences().containsKey("build.spiffs_end")) {
        System.err.println();
        editor.statusError("SPIFFS Not Defined for " + BaseNoGui.getBoardPreferences().get("name"));
        return;
    }
    long spiStart, spiEnd, spiPage, spiBlock;
    try {
        spiStart = getIntPref("build.spiffs_start");
        spiEnd = getIntPref("build.spiffs_end");
        spiPage = getIntPref("build.spiffs_pagesize");
        if (spiPage == 0)
            spiPage = 256;
        spiBlock = getIntPref("build.spiffs_blocksize");
        if (spiBlock == 0)
            spiBlock = 4096;
    } catch (Exception e) {
        editor.statusError(e);
        return;
    }

    TargetPlatform platform = BaseNoGui.getTargetPlatform();

    //Make sure mkspiffs binary exists
    String mkspiffsCmd;
    if (PreferencesData.get("runtime.os").contentEquals("windows"))
        mkspiffsCmd = "mkspiffs.exe";
    else
        mkspiffsCmd = "mkspiffs";

    File tool = new File(platform.getFolder() + "/tools", mkspiffsCmd);
    if (!tool.exists() || !tool.isFile()) {
        tool = new File(platform.getFolder() + "/tools/mkspiffs", mkspiffsCmd);
        if (!tool.exists()) {
            tool = new File(PreferencesData.get("runtime.tools.mkspiffs.path"), mkspiffsCmd);
            if (!tool.exists()) {
                System.err.println();
                editor.statusError("SPIFFS Error: mkspiffs not found!");
                return;
            }
        }
    }

    Boolean isNetwork = false;
    File espota = new File(platform.getFolder() + "/tools");
    File esptool = new File(platform.getFolder() + "/tools");
    String serialPort = PreferencesData.get("serial.port");

    //make sure the serial port or IP is defined
    if (serialPort == null || serialPort.isEmpty()) {
        System.err.println();
        editor.statusError("SPIFFS Error: serial port not defined!");
        return;
    }

    //find espota if IP else find esptool
    if (serialPort.split("\\.").length == 4) {
        isNetwork = true;
        String espotaCmd = "espota.py";
        espota = new File(platform.getFolder() + "/tools", espotaCmd);
        if (!espota.exists() || !espota.isFile()) {
            System.err.println();
            editor.statusError("SPIFFS Error: espota not found!");
            return;
        }
    } else {
        String esptoolCmd = platform.getTool("esptool").get("cmd");
        esptool = new File(platform.getFolder() + "/tools", esptoolCmd);
        if (!esptool.exists() || !esptool.isFile()) {
            esptool = new File(platform.getFolder() + "/tools/esptool", esptoolCmd);
            if (!esptool.exists()) {
                esptool = new File(PreferencesData.get("runtime.tools.esptool.path"), esptoolCmd);
                if (!esptool.exists()) {
                    System.err.println();
                    editor.statusError("SPIFFS Error: esptool not found!");
                    return;
                }
            }
        }
    }

    //load a list of all files
    int fileCount = 0;
    File dataFolder = new File(editor.getSketch().getFolder(), "data");
    if (!dataFolder.exists()) {
        dataFolder.mkdirs();
    }
    if (dataFolder.exists() && dataFolder.isDirectory()) {
        File[] files = dataFolder.listFiles();
        if (files.length > 0) {
            for (File file : files) {
                if ((file.isDirectory() || file.isFile()) && !file.getName().startsWith("."))
                    fileCount++;
            }
        }
    }

    String dataPath = dataFolder.getAbsolutePath();
    String toolPath = tool.getAbsolutePath();
    String sketchName = editor.getSketch().getName();
    String imagePath = getBuildFolderPath(editor.getSketch()) + "\\" + sketchName + ".spiffs.bin";
    String resetMethod = BaseNoGui.getBoardPreferences().get("upload.resetmethod");
    String uploadSpeed = BaseNoGui.getBoardPreferences().get("upload.speed");
    String uploadAddress = BaseNoGui.getBoardPreferences().get("build.spiffs_start");

    Object[] options = { "Yes", "No" };
    String title = "SPIFFS Create";
    String message = "No files have been found in your data folder!\nAre you sure you want to create an empty SPIFFS image?";

    if (fileCount == 0 && JOptionPane.showOptionDialog(editor, message, title, JOptionPane.YES_NO_OPTION,
            JOptionPane.QUESTION_MESSAGE, null, options, options[1]) != JOptionPane.YES_OPTION) {
        System.err.println();
        editor.statusError("SPIFFS Warning: mkspiffs canceled!");
        return;
    }

    editor.statusNotice("SPIFFS Creating Image...");
    System.out.println("[SPIFFS] data   : " + dataPath);
    System.out.println("[SPIFFS] size   : " + ((spiEnd - spiStart) / 1024));
    System.out.println("[SPIFFS] page   : " + spiPage);
    System.out.println("[SPIFFS] block  : " + spiBlock);

    try {
        if (listenOnProcess(new String[] { toolPath, "-c", dataPath, "-p", spiPage + "", "-b", spiBlock + "",
                "-s", (spiEnd - spiStart) + "", imagePath }) != 0) {
            System.err.println();
            editor.statusError("SPIFFS Create Failed!");
            return;
        }
    } catch (Exception e) {
        editor.statusError(e);
        editor.statusError("SPIFFS Create Failed!");
        return;
    }

    title = "SPIFFS Copy";
    message = "Would you like a copy of the SPIFFS image in your project folder?";

    if (JOptionPane.showOptionDialog(editor, message, title, JOptionPane.YES_NO_OPTION,
            JOptionPane.QUESTION_MESSAGE, null, options, options[0]) == JOptionPane.YES_OPTION) {
        File source = new File(imagePath);
        File dest = new File(editor.getSketch().getFolder(), "\\" + sketchName + ".spiffs.bin");
        try {
            Files.copy(source.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING);
            System.out.println("Copied SPIFFS image");
        } catch (IOException e) {
            System.out.println(e);
            editor.statusError("Copy SPIFFS image failed");
        }
    }

    editor.statusNotice("SPIFFS Uploading Image...");
    System.out.println("[SPIFFS] upload : " + imagePath);

    if (isNetwork) {
        String pythonCmd;
        if (PreferencesData.get("runtime.os").contentEquals("windows"))
            pythonCmd = "python.exe";
        else
            pythonCmd = "python";

        System.out.println("[SPIFFS] IP     : " + serialPort);
        System.out.println();
        sysExec(new String[] { pythonCmd, espota.getAbsolutePath(), "-i", serialPort, "-s", "-f", imagePath });
    } else {
        System.out.println("[SPIFFS] address: " + uploadAddress);
        System.out.println("[SPIFFS] reset  : " + resetMethod);
        System.out.println("[SPIFFS] port   : " + serialPort);
        System.out.println("[SPIFFS] speed  : " + uploadSpeed);
        System.out.println();
        sysExec(new String[] { esptool.getAbsolutePath(), "-cd", resetMethod, "-cb", uploadSpeed, "-cp",
                serialPort, "-ca", uploadAddress, "-cf", imagePath });
    }
}

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

private boolean checkPng(String errInfo, String rootDir) {
    //Androlib.class, "UNK_DIRNAME"
    String UNK_DIRNAME = "unknown";

    Pattern patternPng = Pattern.compile("ERROR: Failure processing PNG image (.+)");
    Pattern pattern9Png = Pattern.compile("ERROR: 9-patch image (.+) malformed\\.");

    Matcher matcherPng = patternPng.matcher(errInfo);
    Matcher matcher9Png = pattern9Png.matcher(errInfo);

    Map<String, String> replacePng = new HashMap<>();

    while (matcherPng.find()) {
        String png = matcherPng.group(1);
        String desPath = rootDir + File.separatorChar + UNK_DIRNAME + png.substring(rootDir.length());
        replacePng.put(png, desPath);/*w  w w  .  jav  a  2s  . co  m*/
    }

    while (matcher9Png.find()) {
        String png = matcher9Png.group(1);
        String desPath = rootDir + File.separatorChar + UNK_DIRNAME + png.substring(rootDir.length());
        replacePng.put(png, desPath);
    }

    if (replacePng.size() > 0) {
        for (String srcPng : replacePng.keySet()) {
            if (!new File(srcPng).exists()) {
                /**
                 * ?..
                 * ??
                 */
                continue;
            }

            String desPng = replacePng.get(srcPng);
            //
            new File(desPng).getParentFile().mkdirs();

            try {
                //
                Path srcPath = Paths.get(srcPng);
                Path desPath = Paths.get(desPng);
                LogHelper.warning("Found exception png file : " + srcPng);
                Files.copy(srcPath, desPath, StandardCopyOption.REPLACE_EXISTING);

                //okpng?png
                InputStream pngIs;
                if (srcPng.endsWith(".9.png")) {
                    pngIs = this.getClass().getResourceAsStream(SHAKA_9_PNG);
                } else {
                    pngIs = this.getClass().getResourceAsStream(SHAKA_PNG);
                }
                Files.copy(pngIs, srcPath, StandardCopyOption.REPLACE_EXISTING);
                IOUtils.closeQuietly(pngIs);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }

        return true;
    }

    return false;
}

From source file:com.liferay.sync.engine.document.library.handler.GetSyncDLObjectUpdateHandler.java

protected void copyFile(SyncFile sourceSyncFile, SyncFile targetSyncFile) throws Exception {

    if (_logger.isDebugEnabled()) {
        _logger.debug("Copying file {} to {}", sourceSyncFile.getFilePathName(),
                targetSyncFile.getFilePathName());
    }/* w w w  .java  2s . c o m*/

    Path tempFilePath = FileUtil.getTempFilePath(targetSyncFile);

    Files.copy(Paths.get(sourceSyncFile.getFilePathName()), tempFilePath, StandardCopyOption.REPLACE_EXISTING);

    FileKeyUtil.writeFileKey(tempFilePath, String.valueOf(targetSyncFile.getSyncFileId()), false);

    FileUtil.setModifiedTime(tempFilePath, targetSyncFile.getModifiedTime());

    Watcher watcher = WatcherManager.getWatcher(getSyncAccountId());

    watcher.addDownloadedFilePathName(targetSyncFile.getFilePathName());

    boolean exists = FileUtil.exists(Paths.get(targetSyncFile.getFilePathName()));

    try {
        Files.move(tempFilePath, Paths.get(targetSyncFile.getFilePathName()), StandardCopyOption.ATOMIC_MOVE,
                StandardCopyOption.REPLACE_EXISTING);
    } catch (AccessDeniedException ade) {
        _logger.error(ade.getMessage(), ade);

        targetSyncFile.setState(SyncFile.STATE_ERROR);
        targetSyncFile.setUiEvent(SyncFile.UI_EVENT_ACCESS_DENIED_LOCAL);

        SyncFileService.update(targetSyncFile);

        return;
    }

    targetSyncFile.setState(SyncFile.STATE_SYNCED);

    if (GetterUtil.getBoolean(targetSyncFile.getLocalExtraSettingValue("restoreEvent"))) {

        targetSyncFile.unsetLocalExtraSetting("restoreEvent");

        targetSyncFile.setUiEvent(SyncFile.UI_EVENT_RESTORED_REMOTE);
    } else if (exists) {
        targetSyncFile.setUiEvent(SyncFile.UI_EVENT_DOWNLOADED_UPDATE);
    } else {
        targetSyncFile.setUiEvent(SyncFile.UI_EVENT_DOWNLOADED_NEW);
    }

    SyncFileService.update(targetSyncFile);

    IODeltaUtil.copyChecksums(sourceSyncFile, targetSyncFile);
}

From source file:hydrograph.ui.dataviewer.filemanager.DataViewerFileManager.java

private void copyFilteredFileToDataViewerStagingArea(JobDetails jobDetails, String csvFilterFileAbsolutePath,
        String dataViewerDebugFile) throws IOException, JSchException {
    if (!jobDetails.isRemote()) {
        String sourceFile = csvFilterFileAbsolutePath.trim();
        File file = new File(dataViewerDebugFile);
        Files.copy(Paths.get(sourceFile), Paths.get(dataViewerDebugFile), StandardCopyOption.REPLACE_EXISTING);
    } else {//from ww  w .ja  v a2s .  c  om
        File file = new File(dataViewerDebugFile);
        SCPUtility.INSTANCE.scpFileFromRemoteServer(jobDetails.getHost(), jobDetails.getUsername(),
                jobDetails.getPassword(), csvFilterFileAbsolutePath.trim(), getDataViewerDebugFilePath());
    }
}