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(Path source, OutputStream out) throws IOException 

Source Link

Document

Copies all bytes from a file to an output stream.

Usage

From source file:at.nonblocking.cliwix.cli.Options.java

void copyDefaultPropertiesTo(File file) throws CliwixCliClientArgumentException {
    try {/*from   w w  w.ja v a2 s . co  m*/
        Files.copy(getDefaultProperties(), file.toPath());
    } catch (IOException e) {
        throw new CliwixCliClientArgumentException("Unable to store config: " + file.getAbsolutePath());
    }
}

From source file:com.bc.fiduceo.post.PostProcessingToolMain_IO_Test.java

@Test
public void acceptanceTest() throws IOException, URISyntaxException, ParseException {
    configDir.mkdirs();//from  w w w  .j  a v  a  2  s  .  com
    final File systemConfigFile = new File(configDir, "system-config.xml");
    Files.write(systemConfigFile.toPath(), "<system-config></system-config>".getBytes());

    final Element rootElement = new Element("post-processing-config")
            .addContent(
                    Arrays.asList(new Element("overwrite"),
                            new Element("post-processings").addContent(
                                    new Element("spherical-distance").addContent(Arrays.asList(
                                            new Element("target").addContent(Arrays.asList(
                                                    new Element("data-type").addContent("Float"),
                                                    new Element("var-name").addContent("post_dist"),
                                                    new Element("dim-name").addContent("matchup_count"))),
                                            new Element("primary-lat-variable")
                                                    .setAttribute("scaleAttrName", "Scale")
                                                    .addContent("amsub-n16_Latitude"),
                                            new Element("primary-lon-variable")
                                                    .setAttribute("scaleAttrName", "Scale")
                                                    .addContent("amsub-n16_Longitude"),
                                            new Element("secondary-lat-variable").addContent("ssmt2-f14_lat"),
                                            new Element("secondary-lon-variable")
                                                    .addContent("ssmt2-f14_lon"))))));

    final Document document = new Document(rootElement);
    final String processingConfigFileName = "processing-config.xml";
    final File file = new File(configDir, processingConfigFileName);
    try (OutputStream stream = Files.newOutputStream(file.toPath())) {
        new XMLOutputter(Format.getPrettyFormat()).output(document, stream);
    }

    dataDir.mkdirs();
    final String filename = "mmd22_amsub-n16_ssmt2-f14_2000-306_2000-312.nc";
    final File src = new File(new File(TestUtil.getTestDataDirectory(), "post-processing"), filename);
    final File target = new File(dataDir, filename);
    Files.copy(src.toPath(), target.toPath());

    final String[] args = { "-c", configDir.getAbsolutePath(), "-i", dataDir.getAbsolutePath(), "-start",
            "2000-306", "-end", "2000-312", "-j", processingConfigFileName };

    PostProcessingToolMain.main(args);

    NetcdfFile netcdfFile = null;
    try {
        netcdfFile = NetcdfFile.open(target.getAbsolutePath());
        final Variable postDistVar = netcdfFile.findVariable("post_dist");
        final Variable matchupDistVar = netcdfFile.findVariable("matchup_spherical_distance");

        assertNotNull(postDistVar);
        assertNotNull(matchupDistVar);

        final Array pDistArr = postDistVar.read();
        final Array mDistArr = matchupDistVar.read();

        final float[] pStorage = (float[]) pDistArr.getStorage();
        final float[] mStorage = (float[]) mDistArr.getStorage();

        assertEquals(4, pStorage.length);
        assertEquals(4, mStorage.length);

        for (int i = 0; i < pStorage.length; i++) {
            assertEquals(pStorage[i], mStorage[i], 1e-3);
        }
    } finally {
        if (netcdfFile != null) {
            netcdfFile.close();
        }
    }
}

From source file:it.tidalwave.bluemarine2.persistence.impl.DefaultPersistenceTest.java

/*******************************************************************************************************************
 *
 ******************************************************************************************************************/
@BeforeMethod//w  w  w. ja  v  a2  s.co m
public void setup() throws IOException {
    underTest = context.getBean(DefaultPersistence.class);
    messageBus = context.getBean(MessageBus.class);
    FileUtils.deleteDirectory(TEST_WORKSPACE.toFile());
    Files.createDirectories(TEST_WORKSPACE);
    Files.copy(TEST_IMPORT_FILE, TEST_IMPORT_FILE_COPY);
}

From source file:com.asociate.managedbean.EventoNuevoManagedBean.java

/**
 *
 * @return//w  w w. j  av a2 s. c  om
 */
public String moverImagen() {
    try {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyymmdd");
        String nombre = sdf.format(this.nuevoEvento.getFhinicio()) + "_" + this.nuevoEvento.getPrivacidad()
                + "_" + ((int) (Math.random() * 100));
        File origen = new File(FacesContext.getCurrentInstance().getExternalContext()
                .getRealPath("/resources/eventos/temporal") + "\\"
                + datosSesion.getUsuarioLogeado().getIdUsuario() + ".jpg");
        File destino = new File(
                FacesContext.getCurrentInstance().getExternalContext().getRealPath("/resources/eventos") + "\\"
                        + nombre + ".jpg");

        Files.copy(origen.toPath(), destino.toPath());
        return this.nuevoEvento.getIdEvento() + ".jpg";
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:controler.util.FileUtil.java

public static String uploadV2(UploadedFile file, String emplacement, Abonne abonne) throws IOException {
    System.out.println("upload");
    //String vmParam = "irisi.projet.upload.path";
    String fullPath = "";
    if (file != null) {
        String path = System.getProperty(vmParam);
        if (path == null) {
            JsfUtil.addErrorMessage(null, "option JVM manquante \"" + vmParam + "\"");
        } else {/* w w  w. ja  va  2  s.c  o  m*/
            File folder = new File(abonne.getCheminDossier() + "\\" + emplacement + "\\");//creer la path qui va contenir notre fichier
            if (!folder.exists()) {
                folder.mkdirs(); // Cration de l'arborescense (dossier et sous dossier)
            }
            System.out.println("file.getFileName() ==> " + file.getFileName());
            String nameModified = file.getFileName().replace('.', ':');
            String[] str = nameModified.split(":");
            String fileName = str[0];
            String extension = str[1];
            String outputPath = abonne.getCheminDossier() + "\\" + emplacement + "\\" + fileName
                    + new Date().getTime() + "." + extension;//hna fin kaytht l fichier selectionn
            System.out.println(outputPath);
            File outputFile = new File(outputPath);
            Files.copy(file.getInputstream(), outputFile.toPath());
            JsfUtil.addSuccessMessage(file.getFileName() + " est bien recu.");
            return outputPath;
        }
    }
    return "";
}

From source file:fi.helsinki.cs.iot.hub.api.handlers.plugins.PluginPostRequestHandler.java

@Override
public Response handleRequest(IotHubRequest request) {
    if (request == null) {
        return getResponseKo(STATUS_NOT_YET_IMPLEMENTED, "Cannot work with no request");
    } else if (request.getMethod() != Method.POST) {
        return getResponseKo(STATUS_METHOD_NOT_SUPPORTED, "Method " + request.getMethod() + " not supported");
    } else if (request.getIdentifiers().size() != 0) {
        return getResponseKo(STATUS_BAD_REQUEST,
                "Cannot work with this request if the number of identifier is greater than 0");
    } else {/*from   w  w w .jav  a  2  s  .  co m*/
        String bodyData = request.getBodyData();
        if (bodyData == null) {
            return getResponseKo(STATUS_BAD_REQUEST, "The data seems to be missing");
        }
        try {
            JSONObject jdata = new JSONObject(bodyData);
            String pluginName = jdata.getString("plugin");
            String packageName = jdata.has("package") ? jdata.getString("package") : null;
            boolean isService = jdata.optBoolean("isService")
                    || PluginRequestHandler.SERVICE.equals(request.getOptions().get("type"));

            Type type = BasicPluginInfo.Type.valueOf(jdata.getString("type"));

            PluginInfo pluginInfo = null;
            ServiceInfo serviceInfo = null;

            if (type == Type.NATIVE) {
                File file = ScriptUtils.decodeBase64ToFile(jdata.getString("file"));
                if (!isService) {
                    PluginManager.getInstance().checkNativePlugin(pluginName, packageName, file);
                } else {
                    return getResponseKo(STATUS_NOT_YET_IMPLEMENTED,
                            "The native service feature is not yet implemented");
                }
                int id = (!isService) ? IotHubDataAccess.getInstance().getPlugins().size()
                        : IotHubDataAccess.getInstance().getServiceInfos().size();
                Path pathInLibFolder = Paths.get(this.libdir.toString(), String.format("native-%s-%s-%d.jar",
                        (!isService) ? "plugin" : "service", pluginName, id));
                Path newPath = Files.copy(Paths.get(file.getAbsolutePath()), pathInLibFolder);
                if (newPath != null) {
                    if (!isService) {
                        pluginInfo = IotHubDataAccess.getInstance().addNativePlugin(pluginName, packageName,
                                newPath.toFile());
                    } else {
                        return getResponseKo(STATUS_NOT_YET_IMPLEMENTED,
                                "The native service feature is not yet implemented");
                        //serviceInfo = IotHubDataAccess.getInstance().addServiceInfo(name, file)
                    }
                }
            } else {
                String script = ScriptUtils.decodeBase64ToString(jdata.getString("file"));
                if (!isService) {
                    PluginManager.getInstance().checkJavacriptPlugin(pluginName, script);
                } else {
                    ServiceManager.getInstance().checkService(pluginName, script);
                }
                int id = (!isService) ? IotHubDataAccess.getInstance().getPlugins().size()
                        : IotHubDataAccess.getInstance().getServiceInfos().size();
                File ld = this.libdir.toFile();
                if (!(ld.exists() && ld.isDirectory())) {
                    System.err.println("Libdir folder " + ld.getAbsolutePath() + " not found");
                }
                Path pathInLibFolder = Paths.get(this.libdir.toString(), String.format("javscript-%s-%s-%d.js",
                        (!isService) ? "plugin" : "service", pluginName, id));
                InputStream stream = new ByteArrayInputStream(script.getBytes(StandardCharsets.UTF_8));
                long written = Files.copy(stream, pathInLibFolder);
                if (written > 0) {
                    if (!isService) {
                        pluginInfo = IotHubDataAccess.getInstance().addJavascriptPlugin(pluginName, packageName,
                                pathInLibFolder.toFile());
                    } else {
                        serviceInfo = IotHubDataAccess.getInstance().addServiceInfo(pluginName,
                                pathInLibFolder.toFile());
                    }
                }
            }

            if (pluginInfo == null && serviceInfo == null) {
                return getResponseKo(STATUS_BAD_REQUEST,
                        String.format("I could not add the %s to the db", (!isService) ? "plugin" : "service"));
            } else {
                return getResponseOk(
                        (!isService) ? pluginInfo.toJSON().toString() : serviceInfo.toJSON().toString());
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return getResponseKo(STATUS_BAD_REQUEST, "The data is not JSON data or is incorrect");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return getResponseKo(STATUS_BAD_REQUEST, "Could not read properly the file in the data");
        } catch (PluginException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return getResponseKo(STATUS_BAD_REQUEST, "The plugin is incorrect " + e.getMessage());
        } catch (ServiceException e) {
            // TODO Auto-generated catch block
            return getResponseKo(STATUS_BAD_REQUEST, "The service is incorrect " + e.getMessage());
        }
    }

}

From source file:dyco4j.instrumentation.internals.CLI.java

private static void processCommandLine(final CommandLine cmdLine) throws IOException {
    final Path _srcRoot = Paths.get(cmdLine.getOptionValue(IN_FOLDER_OPTION));
    final Path _trgRoot = Paths.get(cmdLine.getOptionValue(OUT_FOLDER_OPTION));

    final Predicate<Path> _nonClassFileSelector = p -> !p.toString().endsWith(".class")
            && Files.isRegularFile(p);
    final BiConsumer<Path, Path> _fileCopier = (srcPath, trgPath) -> {
        try {//  w  ww  .  ja v a  2  s.  c  o m
            Files.copy(srcPath, trgPath);
        } catch (final IOException _ex) {
            throw new RuntimeException(_ex);
        }
    };
    processFiles(_srcRoot, _trgRoot, _nonClassFileSelector, _fileCopier);

    final CommandLineOptions _cmdLineOptions = new CommandLineOptions(
            cmdLine.hasOption(TRACE_ARRAY_ACCESS_OPTION), cmdLine.hasOption(TRACE_FIELD_ACCESS_OPTION),
            cmdLine.hasOption(TRACE_METHOD_ARGUMENTS_OPTION), cmdLine.hasOption(TRACE_METHOD_CALL_OPTION),
            cmdLine.hasOption(TRACE_METHOD_RETURN_VALUE_OPTION));
    final Set<Path> _filenames = getFilenames(_srcRoot);
    final Path _programDataFile = Paths.get(PROGRAM_DATA_FILE_NAME);
    final ProgramData _programData = ProgramData.loadData(_programDataFile);
    getMemberId2NameMapping(_filenames, _programData);

    final Predicate<Path> _classFileSelector = p -> p.toString().endsWith(".class");
    final String _methodNameRegex = cmdLine.getOptionValue(METHOD_NAME_REGEX_OPTION, METHOD_NAME_REGEX);
    final BiConsumer<Path, Path> _classInstrumenter = (srcPath, trgPath) -> {
        try {
            final ClassReader _cr = new ClassReader(Files.readAllBytes(srcPath));
            final ClassWriter _cw = new ClassWriter(_cr, ClassWriter.COMPUTE_FRAMES);
            final Map<String, String> _shortFieldName2Id = Collections
                    .unmodifiableMap(_programData.shortFieldName2Id);
            final Map<String, String> _shortMethodName2Id = Collections
                    .unmodifiableMap(_programData.shortMethodName2Id);
            final Map<String, String> _class2superClass = Collections
                    .unmodifiableMap(_programData.class2superClass);
            final ClassVisitor _cv1 = new LoggerInitializingClassVisitor(CLI.ASM_VERSION, _cw);
            final ClassVisitor _cv2 = new TracingClassVisitor(_cv1, _shortFieldName2Id, _shortMethodName2Id,
                    _class2superClass, _methodNameRegex, _cmdLineOptions);
            _cr.accept(_cv2, ClassReader.SKIP_FRAMES);

            Files.write(trgPath, _cw.toByteArray());
        } catch (final IOException _ex) {
            throw new RuntimeException(_ex);
        }
    };
    processFiles(_srcRoot, _trgRoot, _classFileSelector, _classInstrumenter);

    ProgramData.saveData(_programData, _programDataFile);
}

From source file:de.thomasbolz.renamer.Renamer.java

/**
 * Step 2 of the renaming process://from  w ww.j av  a  2  s  . c o m
 * Executes the list of CopyTasks.
 */
public void executeCopyTasks() {
    log.info("Start executing CopyTasks");
    for (Path dir : copyTasks.keySet()) {
        Path targetDir = target.resolve(source.relativize(dir));
        try {
            if (!dir.equals(source)) {
                Files.copy(dir, targetDir);
            }
        } catch (FileAlreadyExistsException e) {
            log.error("Directory already exists " + targetDir, e);
        } catch (IOException e) {
            log.error("IO Exception while trying to create directory " + targetDir, e);
        }
        for (CopyTask task : copyTasks.get(dir)) {
            try {
                //                    updateCurrentCopyTask(task);
                Files.copy(task.getSourceFile(), task.getTargetFile());
            } catch (FileAlreadyExistsException e) {
                log.info("File already exists " + task.getTargetFile());
            } catch (IOException e) {
                log.error("IO Exception while trying to execute CopyTask " + task, e);
            }
        }
    }
    log.info("Finished executing CopyTasks");
}

From source file:it.baeyens.arduino.managers.Manager.java

/**
 * Given a platform description in a json file download and install all
 * needed stuff. All stuff is including all tools and core files and
 * hardware specific libraries. That is (on windows) inclusive the make.exe
 * //  ww w  . j  av a 2s . c  o m
 * @param platform
 * @param monitor
 * @param object
 * @return
 */
static public IStatus downloadAndInstall(ArduinoPlatform platform, boolean forceDownload,
        IProgressMonitor monitor) {

    IStatus status = downloadAndInstall(platform.getUrl(), platform.getArchiveFileName(),
            platform.getInstallPath(), forceDownload, monitor);
    if (!status.isOK()) {
        return status;
    }
    MultiStatus mstatus = new MultiStatus(status.getPlugin(), status.getCode(), status.getMessage(),
            status.getException());

    for (ToolDependency tool : platform.getToolsDependencies()) {
        monitor.setTaskName(InstallProgress.getRandomMessage());
        mstatus.add(tool.install(monitor));
    }
    // On Windows install make from equations.org
    if (Platform.getOS().equals(Platform.OS_WIN32)) {
        try {
            Path makePath = Paths
                    .get(ConfigurationPreferences.getPathExtensionPath().append("make.exe").toString()); //$NON-NLS-1$
            if (!makePath.toFile().exists()) {
                Files.createDirectories(makePath.getParent());
                URL makeUrl = new URL("ftp://ftp.equation.com/make/32/make.exe"); //$NON-NLS-1$
                Files.copy(makeUrl.openStream(), makePath);
                makePath.toFile().setExecutable(true, false);
            }

        } catch (IOException e) {
            mstatus.add(new Status(IStatus.ERROR, Activator.getId(), Messages.Manager_Downloading_make_exe, e));
        }
    }

    return mstatus.getChildren().length == 0 ? Status.OK_STATUS : mstatus;

}

From source file:com.ibm.streamsx.topology.internal.context.remote.ZippedToolkitRemoteContext.java

private static void addAllToZippedArchive(Map<Path, String> starts, Path zipFilePath) throws IOException {
    try (ZipArchiveOutputStream zos = new ZipArchiveOutputStream(zipFilePath.toFile())) {
        for (Path start : starts.keySet()) {
            final String rootEntryName = starts.get(start);
            Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    // Skip pyc files.
                    if (file.getFileName().toString().endsWith(".pyc"))
                        return FileVisitResult.CONTINUE;

                    String entryName = rootEntryName;
                    String relativePath = start.relativize(file).toString();
                    // If empty, file is the start file.
                    if (!relativePath.isEmpty()) {
                        entryName = entryName + "/" + relativePath;
                    }// w  w  w .j a v a2s .  c  om
                    // Zip uses forward slashes
                    entryName = entryName.replace(File.separatorChar, '/');

                    ZipArchiveEntry entry = new ZipArchiveEntry(file.toFile(), entryName);
                    if (Files.isExecutable(file))
                        entry.setUnixMode(0100770);
                    else
                        entry.setUnixMode(0100660);

                    zos.putArchiveEntry(entry);
                    Files.copy(file, zos);
                    zos.closeArchiveEntry();
                    return FileVisitResult.CONTINUE;
                }

                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                        throws IOException {
                    final String dirName = dir.getFileName().toString();
                    // Don't include pyc files or .toolkit 
                    if (dirName.equals("__pycache__"))
                        return FileVisitResult.SKIP_SUBTREE;

                    ZipArchiveEntry dirEntry = new ZipArchiveEntry(dir.toFile(), rootEntryName + "/"
                            + start.relativize(dir).toString().replace(File.separatorChar, '/') + "/");
                    zos.putArchiveEntry(dirEntry);
                    zos.closeArchiveEntry();
                    return FileVisitResult.CONTINUE;
                }
            });
        }
    }
}