Java Code Examples for java.nio.file.Files#copy()

The following examples show how to use java.nio.file.Files#copy() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: CloudNet   File: LocalCloudWrapper.java    License: Apache License 2.0 6 votes vote down vote up
private void setupWrapperJar() {
    Path path = Paths.get("wrapper/CloudNet-Wrapper.jar");
    if (!Files.exists(path)) {
        try {
            System.out.println("Downloading wrapper...");
            URLConnection urlConnection = new URL(WRAPPER_URL).openConnection();
            urlConnection.setRequestProperty("User-Agent",
                                             "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
            urlConnection.connect();
            Files.copy(urlConnection.getInputStream(), path);
            System.out.println("Download completed!");
        } catch (Exception exception) {
            System.err.println("Error on setting up wrapper: " + exception.getMessage());
            return;
        }
    }
}
 
Example 2
private static void copyDirectory(File src, File dest) {
    if (src.list() != null) {
        for (String current : src.list()) {
            final File srcFile = new File(src, current);
            final File destFile = new File(dest, current);

            try {
                Files.copy(srcFile.toPath(), destFile.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);
                if (srcFile.isDirectory()) {
                    copyDirectory(srcFile, destFile);
                }
            } catch (IOException e) {
                throw EmbeddedLogger.ROOT_LOGGER.errorCopyingFile(srcFile.getAbsolutePath(), destFile.getAbsolutePath(), e);
            }
        }
    }
}
 
Example 3
private static void prepareCarbonHomeForOSGiLibTests() throws IOException {
    Files.copy(Paths.get(TestConstants.TARGET_FOLDER, TestConstants.TEST_RESOURCES, Constants.OSGI_LIB,
            TestConstants.ARTIFACT_ONE),
            Paths.get(carbonHome.toString(), Constants.OSGI_LIB, TestConstants.ARTIFACT_ONE));
    Files.copy(Paths.get(TestConstants.TARGET_FOLDER, TestConstants.TEST_RESOURCES, Constants.OSGI_LIB,
            TestConstants.ARTIFACT_TWO),
            Paths.get(carbonHome.toString(), Constants.OSGI_LIB, TestConstants.ARTIFACT_TWO));
    Files.copy(Paths.get(TestConstants.TARGET_FOLDER, TestConstants.TEST_RESOURCES, Constants.OSGI_LIB,
            TestConstants.ARTIFACT_THREE),
            Paths.get(carbonHome.toString(), Constants.OSGI_LIB, TestConstants.ARTIFACT_THREE));
    Files.copy(Paths.get(TestConstants.TARGET_FOLDER, TestConstants.TEST_RESOURCES, Constants.OSGI_LIB,
            TestConstants.ARTIFACT_FOUR),
            Paths.get(carbonHome.toString(), Constants.OSGI_LIB, TestConstants.ARTIFACT_FOUR));
    Files.copy(Paths.get(TestConstants.TARGET_FOLDER, TestConstants.TEST_RESOURCES, Constants.OSGI_LIB,
            TestConstants.ARTIFACT_FIVE),
            Paths.get(carbonHome.toString(), Constants.OSGI_LIB, TestConstants.ARTIFACT_FIVE));
}
 
Example 4
Source Project: studio   File: TreeCopier.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
    CopyOption[] options = new CopyOption[] { REPLACE_EXISTING };
    try {
        Files.copy(file, target.resolve(source.relativize(file)), options);
    } catch (IOException err) {
        logger.error("Unable to copy: " + source + " to " + target.resolve(source.relativize(file)), err);
    }
    return CONTINUE;
}
 
Example 5
@Override
public void actionPerformed (ActionEvent evt)
// ---------------------------------------------------------------------------------//
{
  if (disk == null)
  {
    System.out.println ("No disk");
    return;
  }

  JFileChooser fileChooser = new JFileChooser ();
  fileChooser.setDialogTitle ("Save converted disk");
  String name = disk.getName ();
  fileChooser.setSelectedFile (new File (name + ".dsk"));
  if (fileChooser.showSaveDialog (null) == JFileChooser.APPROVE_OPTION)
  {
    File file = fileChooser.getSelectedFile ();
    try
    {
      Files.copy (disk.getDisk ().getFile ().toPath (), file.toPath ());
      JOptionPane.showMessageDialog (null, "Disk saved");
    }
    catch (IOException e)
    {
      e.printStackTrace ();
    }
  }
}
 
Example 6
@Override
void apply(ModuleSpec.Builder builder) throws IOException {

    int slashLoc = this.path.lastIndexOf('/');
    String name = this.path;

    if (slashLoc > 0) {
        name = this.path.substring(slashLoc + 1);
    }

    String ext = ".jar";
    int dotLoc = name.lastIndexOf('.');
    if (dotLoc > 0) {
        ext = name.substring(dotLoc);
        name = name.substring(0, dotLoc);
    }

    File tmp = TempFileManager.INSTANCE.newTempFile(name, ext);

    try (InputStream artifactIn = getClass().getClassLoader().getResourceAsStream(this.path)) {
        Files.copy(artifactIn, tmp.toPath(), StandardCopyOption.REPLACE_EXISTING);
    }
    final String jarName = tmp.getName().toString();
    final JarFile jarFile = new JarFile(tmp);
    final ResourceLoader jarLoader = ResourceLoaders.createJarResourceLoader(jarName,
            jarFile);
    builder.addResourceRoot(ResourceLoaderSpec.createResourceLoaderSpec(jarLoader));

    if (".war".equals(ext)) {
        final ResourceLoader warLoader = ResourceLoaders.createJarResourceLoader(jarName,
                jarFile,
                "WEB-INF/classes");
        builder.addResourceRoot(ResourceLoaderSpec.createResourceLoaderSpec(warLoader));
    }
}
 
Example 7
Source Project: digdag   File: TestUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static void copyResource(String resource, Path dest)
        throws IOException
{
    if (Files.isDirectory(dest)) {
        Path name = Paths.get(resource).getFileName();
        copyResource(resource, dest.resolve(name));
    }
    else {
        try (InputStream input = Resources.getResource(resource).openStream()) {
            Files.copy(input, dest, REPLACE_EXISTING);
        }
    }
}
 
Example 8
/**
 * Action: copies the specified file.
 *
 * @param file the data url
 * @return a FileNotFoundAction that copies the file's data if the file is not found
 */
static FileNotFoundAction copyData(Path file) {
	return (f,c) -> {
		Files.copy(file, f);
		return true;
	};
}
 
Example 9
Source Project: gitlab4j-api   File: TestRepositoryFileApi.java    License: MIT License 5 votes vote down vote up
@Test
public void testRepositoryFileViaInputStream() throws GitLabApiException, IOException {

    Project project = gitLabApi.getProjectApi().getProject(TEST_NAMESPACE, TEST_PROJECT_NAME);
    assertNotNull(project);

    InputStream in = gitLabApi.getRepositoryFileApi().getRawFile(project.getId(), "master", "README.md");

    Path target = Files.createTempFile(TEST_PROJECT_NAME + "-README", "md");
    Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING);

    assertTrue(target.toFile().length() > 0);
    Files.delete(target);
}
 
Example 10
/**
 * Helper method for handling the ContentSyncManager mocking boilerplate.
 *
 * @param workDir the working directory of the ContentSyncManager
 * @param body the Runnable with the test body
 * @throws Exception if anything goes wrong
 */
private static void withSetupContentSyncManager(String workDir, Runnable body) throws Exception {
    File subJson = new File(TestUtils.findTestData(
            new File(workDir, SUBSCRIPTIONS_JSON).getAbsolutePath()).getPath());
    File orderJson = new File(TestUtils.findTestData(
            new File(workDir, ORDERS_JSON).getAbsolutePath()).getPath());

    Path fromdir = Files.createTempDirectory("sumatest");
    File subtempFile = new File(fromdir.toString(), SUBSCRIPTIONS_JSON);
    File ordertempFile = new File(fromdir.toString(), ORDERS_JSON);
    Files.copy(subJson.toPath(), subtempFile.toPath());
    Files.copy(orderJson.toPath(), ordertempFile.toPath());
    Config.get().setString(ContentSyncManager.RESOURCE_PATH, fromdir.toString());
    try {
        SUSEProductTestUtils.clearAllProducts();
        SUSEProductTestUtils.createVendorSUSEProducts();
        SUSEProductTestUtils.createVendorEntitlementProducts();

        ContentSyncManager cm = new ContentSyncManager();

        // this will also refresh the DB cache of subscriptions
        Collection<SCCSubscriptionJson> s;
        s = cm.updateSubscriptions();
        HibernateFactory.getSession().flush();
        assertNotNull(s);

        body.run();
    }
    finally {
        Config.get().remove(ContentSyncManager.RESOURCE_PATH);
        SUSEProductTestUtils.deleteIfTempFile(subJson);
        SUSEProductTestUtils.deleteIfTempFile(orderJson);
        subtempFile.delete();
        ordertempFile.delete();
        fromdir.toFile().delete();
    }
}
 
Example 11
Source Project: baleen   File: RdfEntityGraphFileTest.java    License: Apache License 2.0 5 votes vote down vote up
private Path createAndFailIfMissing(Path path, URL url, String name)
    throws URISyntaxException, IOException {
  if (url != null) {
    return Paths.get(url.toURI());
  }
  Files.copy(path, Paths.get("src/test/resources/uk/gov/dstl/baleen/consumers/file/", name));
  fail();
  return null;
}
 
Example 12
Source Project: code   File: PDFMessageConverter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object fromMessage(Message message) throws MessageConversionException {
	System.err.println("-----------PDF MessageConverter----------");
	
	byte[] body = message.getBody();
	String fileName = UUID.randomUUID().toString();
	String path = "d:/010_test/" + fileName + ".pdf";
	File f = new File(path);
	try {
		Files.copy(new ByteArrayInputStream(body), f.toPath());
	} catch (IOException e) {
		e.printStackTrace();
	}
	return f;
}
 
Example 13
@Test
public void copyFileToAnotherSystem_theTargetFileShouldExist() throws IOException {
  writeToCache("/source.txt");
  commitToMaster();
  initGitFileSystem();

  GitPath source = gfs.getPath("/source.txt");
  GitPath target = targetGfs.getPath("/target.txt");
  Files.copy(source, target);
  assertTrue(Files.exists(target));
}
 
Example 14
Source Project: che   File: SeleniumTestHandler.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private void captureScreenshotFromCurrentWindow(ITestResult result, SeleniumWebDriver webDriver) {
  String testReference = getTestReference(result);
  String filename = getTestResultFilename(testReference, "png");
  try {
    byte[] data = webDriver.getScreenshotAs(OutputType.BYTES);
    Path screenshot = Paths.get(screenshotsDir, filename);
    Files.createDirectories(screenshot.getParent());
    Files.copy(new ByteArrayInputStream(data), screenshot);
  } catch (WebDriverException | IOException e) {
    LOG.error(format("Can't capture screenshot for test %s", testReference), e);
  }
}
 
Example 15
Source Project: mmtf-spark   File: DrugBankDataset.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Saves tabular report as a temporary CSV file.
 * 
 * @param input
 * @return path to temporary file
 * @throws IOException
 */
private static Path saveTempFile(InputStream input) throws IOException {
    Path tempFile = Files.createTempFile(null, ".csv");
    Files.copy(input, tempFile, StandardCopyOption.REPLACE_EXISTING);
    input.close();

    // TODO delete tempFile
    return tempFile;
}
 
Example 16
Source Project: bazel   File: ResourcesZip.java    License: Apache License 2.0 4 votes vote down vote up
void writeResourcesConfigTo(Path resourcesConfigOut) throws Exception {
  Files.copy(resourcesConfig, resourcesConfigOut);
}
 
Example 17
Source Project: Bytecoder   File: ModulePath.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Reads a packaged or exploded module, returning a {@code ModuleReference}
 * to the module. Returns {@code null} if the entry is not recognized.
 *
 * @throws IOException if an I/O error occurs
 * @throws FindException if an error occurs parsing its module descriptor
 */
private ModuleReference readModule(Path entry, BasicFileAttributes attrs)
    throws IOException
{
    try {

        // exploded module
        if (attrs.isDirectory()) {
            return readExplodedModule(entry); // may return null
        }

        // JAR or JMOD file
        if (attrs.isRegularFile()) {
            String fn = entry.getFileName().toString();
            boolean isDefaultFileSystem = isDefaultFileSystem(entry);

            // JAR file
            if (fn.endsWith(".jar")) {
                if (isDefaultFileSystem) {
                    return readJar(entry);
                } else {
                    // the JAR file is in a custom file system so
                    // need to copy it to the local file system
                    Path tmpdir = Files.createTempDirectory("mlib");
                    Path target = Files.copy(entry, tmpdir.resolve(fn));
                    return readJar(target);
                }
            }

            // JMOD file
            if (isDefaultFileSystem && isLinkPhase && fn.endsWith(".jmod")) {
                return readJMod(entry);
            }
        }

        return null;

    } catch (InvalidModuleDescriptorException e) {
        throw new FindException("Error reading module: " + entry, e);
    }
}
 
Example 18
@Override
public void copy(Path source, Path target, CopyOption... options) throws IOException {
    triggerEx(source, "copy");
    Files.copy(unwrap(source), unwrap(target), options);
}
 
Example 19
@Override
public void copy(Path source, Path target, CopyOption... options)
		throws IOException {
	Files.copy(EncryptedFileSystem.dismantle(source),
			EncryptedFileSystem.dismantle(target), options);
}
 
Example 20
public static ResourceLoader loaderFor(URL base, String rootPath, String loaderPath, String loaderName) throws IOException {

        //System.err.println( "** " + base + ", " + rootPath + ", " + loaderPath + ", " + loaderName );

        if (base.toExternalForm().startsWith("jar:file:")) {
            int endLoc = base.toExternalForm().indexOf(".jar!");
            if (endLoc > 0) {
                String jarPath = base.toExternalForm().substring(9, endLoc + 4);

                File exp = exploded.get(jarPath);

                if (exp == null) {
                    exp = TempFileManager.INSTANCE.newTempDirectory( "module-jar", ".jar_d" );

                    JarFile jarFile = new JarFile(jarPath);

                    Enumeration<JarEntry> entries = jarFile.entries();

                    while (entries.hasMoreElements()) {
                        JarEntry each = entries.nextElement();

                        if (!each.isDirectory()) {
                            File out = new File(exp, each.getName());
                            out.getParentFile().mkdirs();
                            Files.copy(jarFile.getInputStream(each), out.toPath(), StandardCopyOption.REPLACE_EXISTING);
                        }
                    }
                }

                String relativeRoot = base.toExternalForm().substring(endLoc + 5);
                File resourceRoot = new File(new File(exp, relativeRoot), loaderPath);
                /*
                if ( resourceRoot.listFiles() != null ) {
                    System.err.println("@ " + resourceRoot + " --> " + Arrays.asList(resourceRoot.listFiles()));
                }
                */
                return ResourceLoaders.createFileResourceLoader(loaderName, resourceRoot);
            }
        }

        return ResourceLoaders.createFileResourceLoader(loaderPath, new File(rootPath));
    }