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:com.github.podd.resources.test.AbstractResourceImplTest.java

/**
 * Builds a {@link Representation} from a Resource.
 *
 * @param resourcePath/*w  w w.j  a v  a 2  s .co m*/
 * @param mediaType
 * @return
 * @throws IOException
 */
protected FileRepresentation buildRepresentationFromResource(final String resourcePath,
        final MediaType mediaType) throws IOException {
    final Path target = this.testDir
            .resolve(UUID.randomUUID().toString() + "." + Paths.get(resourcePath).getFileName());

    try (final InputStream input = this.getClass().getResourceAsStream(resourcePath)) {
        Files.copy(input, target, StandardCopyOption.REPLACE_EXISTING);
    }

    final FileRepresentation fileRep = new FileRepresentation(target.toFile(), mediaType);
    return fileRep;
}

From source file:gov.vha.isaac.rf2.filter.RF2Filter.java

private void handleFile(Path inputFile, Path outputFile) throws IOException {
    boolean justCopy = true;
    boolean justSkip = false;

    if (inputFile.toFile().getName().toLowerCase().endsWith(".txt")) {
        justCopy = false;//from  w  w w.j  a  va  2s  .  co m
        //Filter the file
        BufferedReader fileReader = new BufferedReader(
                new InputStreamReader(new BOMInputStream(new FileInputStream(inputFile.toFile())), "UTF-8"));
        BufferedWriter fileWriter = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(outputFile.toFile()), "UTF-8"));
        PipedOutputStream pos = new PipedOutputStream();
        PipedInputStream pis = new PipedInputStream(pos);
        CSVReader csvReader = new CSVReader(new InputStreamReader(pis), '\t', CSVParser.NULL_CHARACTER); //don't look for quotes, the data is bad, and has floating instances of '"' all by itself

        boolean firstLine = true;
        String line = null;
        long kept = 0;
        long skipped = 0;
        long total = 0;

        int moduleColumn = -1;

        while ((line = fileReader.readLine()) != null) {
            total++;
            //Write this line into the CSV parser
            pos.write(line.getBytes());
            pos.write("\r\n".getBytes());
            pos.flush();
            String[] fields = csvReader.readNext();

            boolean correctModule = false;
            for (String ms : moduleStrings_) {
                if (moduleColumn >= 0 && fields[moduleColumn].equals(ms)) {
                    correctModule = true;
                    break;
                }
            }

            if (firstLine || correctModule) {
                kept++;
                fileWriter.write(line);
                fileWriter.write("\r\n");
            } else {
                //don't write line
                skipped++;
            }

            if (firstLine) {

                log("Filtering file " + inputDirectory.toPath().relativize(inputFile).toString());
                firstLine = false;
                if (fields.length < 2) {
                    log("txt file doesn't look like a data file - abort and just copy.");
                    justCopy = true;
                    break;
                }
                for (int i = 0; i < fields.length; i++) {
                    if (fields[i].equals("moduleId")) {
                        moduleColumn = i;
                        break;
                    }
                }
                if (moduleColumn < 0) {
                    log("No moduleId column found - skipping file");
                    justSkip = true;
                    break;
                }
            }
        }

        fileReader.close();
        csvReader.close();
        fileWriter.close();

        if (!justCopy) {
            log("Kept " + kept + " Skipped " + skipped + " out of " + total + " lines in "
                    + inputDirectory.toPath().relativize(inputFile).toString());
        }
    }

    if (justCopy) {
        //Just copy the file
        Files.copy(inputFile, outputFile, StandardCopyOption.REPLACE_EXISTING);
        log("Copied file " + inputDirectory.toPath().relativize(inputFile).toString());
    }

    if (justSkip) {
        Files.delete(outputFile);
        log("Skipped file " + inputDirectory.toPath().relativize(inputFile).toString()
                + " because it doesn't contain a moduleId");
    }
}

From source file:cn.edu.zjnu.acm.judge.core.Judger.java

private boolean compile(RunRecord runRecord) throws IOException {
    String source = runRecord.getSource();
    if (StringUtils.isEmptyOrWhitespace(source)) {
        return false;
    }//from   w ww .  j a v a  2s .com
    Path work = runRecord.getWorkDirectory();
    final String main = "Main";
    Files.createDirectories(work);
    Path sourceFile = work.resolve(main + "." + runRecord.getLanguage().getSourceExtension()); //???
    Files.copy(new ByteArrayInputStream(source.getBytes(Platform.getCharset())), sourceFile,
            StandardCopyOption.REPLACE_EXISTING);

    String compileCommand = runRecord.getLanguage().getCompileCommand();
    log.debug("Compile Command: {}", compileCommand); //
    if (StringUtils.isEmptyOrWhitespace(compileCommand)) {
        return true;
    }
    assert compileCommand != null;
    //
    // VC++?
    // G++?
    Path compileInfo = work.resolve("compileinfo.txt");
    Process process = ProcessCreationHelper.execute(new ProcessBuilder(compileCommand.split("\\s+"))
            .directory(work.toFile()).redirectOutput(compileInfo.toFile()).redirectErrorStream(true)::start);
    process.getInputStream().close();
    try {
        process.waitFor(45, TimeUnit.SECONDS);
    } catch (InterruptedException ex) {
        throw new InterruptedIOException();
    }
    //?
    String errorInfo;
    if (process.isAlive()) {
        process.destroy();
        try {
            process.waitFor();
        } catch (InterruptedException ex) {
            throw new InterruptedIOException();
        }
        errorInfo = "Compile timeout\nOutput:\n" + collectLines(compileInfo);
    } else {
        errorInfo = collectLines(compileInfo);
    }
    log.debug("errorInfo = {}", errorInfo);
    Path executable = work.resolve(main + "." + runRecord.getLanguage().getExecutableExtension()); //??
    log.debug("executable = {}", executable);
    boolean compileOK = Files.exists(executable);
    //
    if (!compileOK) {
        submissionMapper.updateResult(runRecord.getSubmissionId(), ResultType.COMPILE_ERROR, 0, 0);
        submissionMapper.saveCompileInfo(runRecord.getSubmissionId(), errorInfo);
        updateSubmissionStatus(runRecord);
    }
    return compileOK;
}

From source file:dialog.DialogFunctionUser.java

private void actionEditUser() {
    if (!isValidData()) {
        return;//from  w  ww . j ava  2  s.  c  o  m
    }
    if (!isValidData()) {
        return;
    }
    String username = tfUsername.getText();
    String fullname = tfFullname.getText();
    String password = mUser.getPassword();
    if (tfPassword.getPassword().length == 0) {
        password = new String(tfPassword.getPassword());
        password = LibraryString.md5(password);
    }
    int role = cbRole.getSelectedIndex();
    if (mAvatar != null) {
        User objUser = new User(mUser.getIdUser(), username, password, fullname, role,
                new Date(System.currentTimeMillis()), mAvatar.getPath());
        if (mControllerUser.editItem(objUser, mRow)) {
            String fileName = FilenameUtils.getBaseName(mAvatar.getName()) + "-" + System.nanoTime() + "."
                    + FilenameUtils.getExtension(mAvatar.getName());
            Path source = Paths.get(mAvatar.toURI());
            Path destination = Paths.get("files/" + fileName);
            Path pathOldAvatar = Paths.get(mUser.getAvatar());
            try {
                Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
                Files.deleteIfExists(pathOldAvatar);
            } catch (IOException ex) {
                Logger.getLogger(DialogFunctionRoom.class.getName()).log(Level.SEVERE, null, ex);
            }
            ImageIcon icon = new ImageIcon(getClass().getResource("/images/ic_success.png"));
            JOptionPane.showMessageDialog(this.getParent(), "Sa thnh cng", "Success",
                    JOptionPane.INFORMATION_MESSAGE, icon);
        } else {
            JOptionPane.showMessageDialog(this.getParent(), "Sa tht bi", "Fail",
                    JOptionPane.ERROR_MESSAGE);
        }
    } else {
        User objUser = new User(mUser.getIdUser(), username, password, fullname, role,
                new Date(System.currentTimeMillis()), mUser.getAvatar());
        if (mControllerUser.editItem(objUser, mRow)) {
            ImageIcon icon = new ImageIcon(getClass().getResource("/images/ic_success.png"));
            JOptionPane.showMessageDialog(this.getParent(), "Sa thnh cng", "Success",
                    JOptionPane.INFORMATION_MESSAGE, icon);
        } else {
            JOptionPane.showMessageDialog(this.getParent(), "Sa tht bi", "Fail",
                    JOptionPane.ERROR_MESSAGE);
        }
    }
    this.dispose();
}

From source file:fr.inria.soctrace.tools.ocelotl.core.caches.DichotomyCache.java

/**
 * Save the cache of the current trace to the specified path
 * /*from   w w  w  .ja va2s  .c  o m*/
 * @param oParam
 *            current parameters
 * @param destPath
 *            path to save the file
 */
public void saveDichotomyCacheTo(OcelotlParameters oParam, String destPath) {
    // Get the current cache file
    CacheParameters params = new CacheParameters(oParam);
    File source = null;

    // Look for the corresponding file
    for (CacheParameters par : cachedDichotomy.keySet()) {
        if (similarParameters(params, par)) {
            source = cachedDichotomy.get(par);
        }
    }

    if (source != null) {
        File dest = new File(destPath);

        try {
            Files.copy(source.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else {
        logger.error("[DICHOTOMY CACHE] No corresponding cache file was found");
    }
}

From source file:com.kantenkugel.discordbot.jdocparser.JDoc.java

private static void download() {
    try {/*from w  w  w . j  a  v a2s.c  o m*/
        JenkinsBuild lastBuild = JenkinsApi.JDA_JENKINS.getLastSuccessfulBuild();
        if (lastBuild != null) {
            JDocUtil.LOG.debug("Downloading JDA docs...");
            ResponseBody body = null;
            try {
                String artifactUrl = lastBuild.artifacts.get("JDA-javadoc").getLink();
                Response res = Bot.httpClient.newCall(new Request.Builder().url(artifactUrl).get().build())
                        .execute();
                if (!res.isSuccessful()) {
                    JDocUtil.LOG.warn("OkHttp returned failure for " + artifactUrl);
                    return;
                }
                body = res.body();
                final InputStream is = body.byteStream();
                Files.copy(is, JDocUtil.LOCAL_DOC_PATH, StandardCopyOption.REPLACE_EXISTING);
                is.close();
                JDocUtil.LOG.debug("Done downloading JDA docs");
            } catch (Exception e) {
                JDocUtil.LOG.error("Error downloading jdoc jar", e);
            } finally {
                if (body != null)
                    body.close();
            }
        } else {
            JDocUtil.LOG.warn("There was no Jenkins build?! Skipping download");
        }
    } catch (IOException ex) {
        JDocUtil.LOG.warn("Could not contact Jenkins, skipping download");
    }
}

From source file:org.elasticsearch.test.rest.yaml.ESClientYamlSuiteTestCase.java

/**
 * Returns a new FileSystem to read REST resources, or null if they
 * are available from classpath.//  w w w  .ja v a  2s.  co  m
 */
@SuppressForbidden(reason = "proper use of URL, hack around a JDK bug")
protected static FileSystem getFileSystem() throws IOException {
    // REST suite handling is currently complicated, with lots of filtering and so on
    // For now, to work embedded in a jar, return a ZipFileSystem over the jar contents.
    URL codeLocation = FileUtils.class.getProtectionDomain().getCodeSource().getLocation();
    boolean loadPackaged = RandomizedTest.systemPropertyAsBoolean(REST_LOAD_PACKAGED_TESTS, true);
    if (codeLocation.getFile().endsWith(".jar") && loadPackaged) {
        try {
            // hack around a bug in the zipfilesystem implementation before java 9,
            // its checkWritable was incorrect and it won't work without write permissions.
            // if we add the permission, it will open jars r/w, which is too scary! so copy to a safe r-w location.
            Path tmp = Files.createTempFile(null, ".jar");
            try (InputStream in = FileSystemUtils.openFileURLStream(codeLocation)) {
                Files.copy(in, tmp, StandardCopyOption.REPLACE_EXISTING);
            }
            return FileSystems.newFileSystem(new URI("jar:" + tmp.toUri()), Collections.emptyMap());
        } catch (URISyntaxException e) {
            throw new IOException("couldn't open zipfilesystem: ", e);
        }
    } else {
        return null;
    }
}

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

private void copyCSVDebugFileToDataViewerStagingArea(JobDetails jobDetails, String csvDebugFileAbsolutePath,
        String dataViewerDebugFile, boolean isOverWritten) throws IOException, JSchException {
    if (!jobDetails.isRemote()) {
        String sourceFile = csvDebugFileAbsolutePath.trim();
        File file = new File(dataViewerDebugFile);
        if (!file.exists() || isOverWritten) {
            Files.copy(Paths.get(sourceFile), Paths.get(dataViewerDebugFile),
                    StandardCopyOption.REPLACE_EXISTING);
        }//from   w w w .j  a  v  a 2 s. co m
    } else {
        File file = new File(dataViewerDebugFile);
        if (!file.exists() || isOverWritten) {
            SCPUtility.INSTANCE.scpFileFromRemoteServer(jobDetails.getHost(), jobDetails.getUsername(),
                    jobDetails.getPassword(), csvDebugFileAbsolutePath.trim(), getDataViewerDebugFilePath());
        }
    }
}

From source file:com.codesourcery.internal.installer.ui.pages.ResultsPage.java

/**
 * Copy the log file to a location outside of the default configuration 
 * area so that it's accessible after the installer has exited and self-deleted.
 *//*  w  ww  .  jav a2  s  .  co  m*/
private void copyLog() {

    if (logFile != null) {
        // Already copied log.
        return;
    }

    IPath logDirPath = Installer.getDefault().getLogPath();
    try {
        // Copy the platform log file
        if (Installer.getDefault().isCopyLog()) {
            File originalLogFile = Platform.getLogFileLocation().toFile();
            logFile = logDirPath.append(originalLogFile.getName()).toFile();
            Files.copy(originalLogFile.toPath(), logFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        }
        // Use the platform log file
        else {
            logFile = Platform.getLogFileLocation().toFile();
        }
    } catch (IOException e) {
        Installer.log(e);
    }
}

From source file:codes.thischwa.c5c.impl.LocalConnector.java

@Override
public void upload(String urlDirectory, String sanitizedName, InputStream in) throws C5CException {
    Path parentFolder = buildRealPathAndCheck(urlDirectory);
    Path fileToSave = parentFolder.resolve(sanitizedName);
    try {/*from   w w w  .j a va 2 s  . c  o m*/
        Files.deleteIfExists(fileToSave);
        Files.copy(in, fileToSave, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        throw new FilemanagerException(FilemanagerAction.UPLOAD, FilemanagerException.Key.InvalidFileUpload,
                sanitizedName);
    }
}