java.nio.file.StandardCopyOption源码实例Demo

java.io.SyncFailedException#java.nio.file.StandardCopyOption源码实例Demo

下面列出了java.io.SyncFailedException#java.nio.file.StandardCopyOption 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: arcusplatform   文件: BackupService.java
private static void updateApplicationDb(@Nullable Db restoreDb, File path) {
   try {
      File appDbPath = DbService.getApplicationDbPath();

      Path updatedDbPath = FileSystems.getDefault().getPath(path.getAbsolutePath());
      Path existingDbPath = FileSystems.getDefault().getPath(appDbPath.getAbsolutePath());

      Files.move(updatedDbPath, existingDbPath, StandardCopyOption.REPLACE_EXISTING);

      if (restoreDb != null) {
         restoreDb.close();
      }

      DbService.reloadApplicationDb();
   } catch (IOException ex) {
      log.warn("could not overwrite application database with backup copy:", ex);
      throw new RuntimeException(ex);
   }
}
 
源代码2 项目: ecosys   文件: Util.java
public static File getClientLogFile(String file, String username, String serverip,
    boolean rotate) throws IOException {
  if (Util.LOG_DIR == null) {
    throw new IOException("LogDir is null");
  }

  String filename = Util.LOG_DIR + "/" + file + ".";
  filename += Math.abs((username + "." + serverip).hashCode()) % 1000000;
  File f = new File(filename);
  if (!f.getParentFile().isDirectory()) {
    f.getParentFile().mkdirs();
  }

  if (!f.exists()) {
    //create file if it does not exist
    f.createNewFile();
  } else if (rotate && f.length() > Constant.LogRotateSize) {
    // rotate log file when file is large than 500M
    long current = System.currentTimeMillis();
    // copy the log to a new file with timestamp
    String LogCopy = filename + "." + current / 1000;
    Files.move(f.toPath(), Paths.get(LogCopy), StandardCopyOption.REPLACE_EXISTING);
  }

  return f;
}
 
源代码3 项目: jdk8u60   文件: ReplayCacheTestProc.java
private static Ex round(int i, int old, int server, boolean expected)
        throws Exception {
    ps[server].println("TEST");
    ps[server].println(reqs.get(old).msg);
    String reply = ps[server].readData();
    Ex result = new Ex();
    result.i = i;
    result.expected = expected;
    result.server = ps[server].debug();
    result.actual = Boolean.valueOf(reply);
    result.user = reqs.get(old).user;
    result.peer = reqs.get(old).peer;
    result.old = old;
    result.csize = csize(result.peer);
    result.hash = hash(reqs.get(old).msg);
    if (new File(dfl(result.peer)).exists()) {
        Files.copy(Paths.get(dfl(result.peer)), Paths.get(
            String.format("%03d-USER%d-host%d-%s-%s",
                i, result.user, result.peer, result.server,
                result.actual)
            + "-" + result.hash),
            StandardCopyOption.COPY_ATTRIBUTES);
    }
    return result;
}
 
源代码4 项目: Plan   文件: ConfigUpdaterTest.java
@BeforeAll
static void prepareConfigFiles() throws URISyntaxException, IOException {
    oldConfig = tempDir.resolve("config.yml").toFile();
    File configResource = TestResources.getTestResourceFile("config/4.5.2-config.yml", ConfigUpdater.class);
    Files.copy(configResource.toPath(), oldConfig.toPath(), StandardCopyOption.REPLACE_EXISTING);

    oldBungeeConfig = tempDir.resolve("bungeeconfig.yml").toFile();
    File bungeeConfigResource = TestResources.getTestResourceFile("config/4.5.2-bungeeconfig.yml", ConfigUpdater.class);
    Files.copy(bungeeConfigResource.toPath(), oldBungeeConfig.toPath(), StandardCopyOption.REPLACE_EXISTING);

    newConfig = tempDir.resolve("newconfig.yml");
    TestResources.copyResourceIntoFile(newConfig.toFile(), "/assets/plan/config.yml");

    newBungeeConfig = tempDir.resolve("newbungeeconfig.yml");
    TestResources.copyResourceIntoFile(newBungeeConfig.toFile(), "/assets/plan/bungeeconfig.yml");

    PluginLogger testLogger = new TestPluginLogger();
    errorLogger = Mockito.mock(ErrorLogger.class);
    UNDER_TEST = new ConfigUpdater(testLogger, errorLogger);
}
 
源代码5 项目: spring-javaformat   文件: CheckTaskTests.java
private void copyFolder(Path source, Path target) throws IOException {
	try (Stream<Path> stream = Files.walk(source)) {
		stream.forEach((child) -> {
			try {
				Path relative = source.relativize(child);
				Path destination = target.resolve(relative);
				if (!destination.toFile().isDirectory()) {
					Files.copy(child, destination, StandardCopyOption.REPLACE_EXISTING);
				}
			}
			catch (Exception ex) {
				throw new IllegalStateException(ex);
			}
		});
	}
}
 
/** */
private void copyIncompatibleBinaryMetadata(String fromWorkDir,
    String fromConsId,
    String toWorkDir,
    String toConsId,
    String fileName
) throws Exception {
    String workDir = U.defaultWorkDirectory();

    Path fromFile = Paths.get(workDir, fromWorkDir, DataStorageConfiguration.DFLT_BINARY_METADATA_PATH,
        fromConsId, fileName);
    Path toFile = Paths.get(workDir, toWorkDir, DataStorageConfiguration.DFLT_BINARY_METADATA_PATH,
        toConsId, fileName);

    Files.copy(fromFile, toFile, StandardCopyOption.REPLACE_EXISTING);
}
 
源代码7 项目: mycore   文件: MCRUploadHandlerIFS.java
private InputStream preprocessInputStream(String path, InputStream in, long length, Supplier<Path> tempFileSupplier)
    throws IOException {
    List<MCRPostUploadFileProcessor> activeProcessors = FILE_PROCESSORS.stream().filter(p -> p.isProcessable(path))
        .collect(Collectors.toList());
    if (activeProcessors.isEmpty()) {
        return in;
    }
    Path currentTempFile = tempFileSupplier.get();
    try (InputStream initialIS = in) {
        Files.copy(initialIS, currentTempFile, StandardCopyOption.REPLACE_EXISTING);
    }
    long myLength = Files.size(currentTempFile);
    if (length >= 0 && length != myLength) {
        throw new IOException("Length of transmitted data does not match promised length: " + myLength + "!="
            + length);
    }
    for (MCRPostUploadFileProcessor pufp : activeProcessors) {
        currentTempFile = pufp.processFile(path, currentTempFile, tempFileSupplier);
    }
    return Files.newInputStream(currentTempFile);
}
 
源代码8 项目: openjdk-jdk8u   文件: ProcessAttachDebuggee.java
public static void main(String args[]) throws Exception {
    // bind to a random port
    ServerSocket ss = new ServerSocket(0);
    int port = ss.getLocalPort();

    // Write the port number to the given file
    File partial = new File(args[0] + ".partial");
    File portFile = new File(args[0]);
    try (FileOutputStream fos = new FileOutputStream(partial)) {
        fos.write( Integer.toString(port).getBytes("UTF-8") );
    }
    Files.move(partial.toPath(), portFile.toPath(), StandardCopyOption.ATOMIC_MOVE);

    System.out.println("Debuggee bound to port: " + port);
    System.out.flush();

    // wait for test harness to connect
    Socket s = ss.accept();
    s.close();
    ss.close();

    System.out.println("Debuggee shutdown.");
}
 
源代码9 项目: openjdk-jdk9   文件: JImageGenerator.java
public static Path addFiles(Path module, InMemoryFile... resources) throws IOException {
    Path tempFile = Files.createTempFile("jlink-test", "");
    try (JarInputStream in = new JarInputStream(Files.newInputStream(module));
         JarOutputStream out = new JarOutputStream(new FileOutputStream(tempFile.toFile()))) {
        ZipEntry entry;
        while ((entry = in.getNextEntry()) != null) {
            String name = entry.getName();
            out.putNextEntry(new ZipEntry(name));
            copy(in, out);
            out.closeEntry();
        }
        for (InMemoryFile r : resources) {
            addFile(r, out);
        }
    }
    Files.move(tempFile, module, StandardCopyOption.REPLACE_EXISTING);
    return module;
}
 
源代码10 项目: wildfly-maven-plugin   文件: Archives.java
private static Path getArchive(final Path path) throws IOException {
    final Path result;
    // Get the extension
    final String fileName = path.getFileName().toString();
    final String loweredFileName = fileName.toLowerCase(Locale.ENGLISH);
    if (loweredFileName.endsWith(".gz")) {
        String tempFileName = fileName.substring(0, loweredFileName.indexOf(".gz"));
        final int index = tempFileName.lastIndexOf('.');
        if (index > 0) {
            result = Files.createTempFile(tempFileName.substring(0, index), tempFileName.substring(index));
        } else {
            result = Files.createTempFile(tempFileName.substring(0, index), "");
        }
        try (CompressorInputStream in = new CompressorStreamFactory().createCompressorInputStream(new BufferedInputStream(Files.newInputStream(path)))) {
            Files.copy(in, result, StandardCopyOption.REPLACE_EXISTING);
        } catch (CompressorException e) {
            throw new IOException(e);
        }
    } else {
        result = path;
    }
    return result;
}
 
源代码11 项目: nifi-registry   文件: ClientUtils.java
public static File getExtensionBundleVersionContent(final Response response, final File outputDirectory) {
    final String contentDispositionHeader = response.getHeaderString("Content-Disposition");
    if (StringUtils.isBlank(contentDispositionHeader)) {
        throw new IllegalStateException("Content-Disposition header was blank or missing");
    }

    final int equalsIndex = contentDispositionHeader.lastIndexOf("=");
    final String filename = contentDispositionHeader.substring(equalsIndex + 1).trim();
    final File bundleFile = new File(outputDirectory, filename);

    try (final InputStream responseInputStream = response.readEntity(InputStream.class)) {
        Files.copy(responseInputStream, bundleFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        return bundleFile;
    } catch (Exception e) {
        throw new IllegalStateException("Unable to write bundle content due to: " + e.getMessage(), e);
    }
}
 
public static void setClasspath(IClasspathEntry[] classpath, IJavaProject javaProject, IProgressMonitor monitor) throws JavaModelException
{
	// backup .classpath
	File classPathFileBak = javaProject.getProject().getFile(".classpath.bak").getLocation().toFile();
	if (!classPathFileBak.exists())
	{
		File classPathFile = javaProject.getProject().getFile(".classpath").getLocation().toFile();
		try {
			Files.copy(Paths.get(classPathFile.getAbsolutePath()), Paths.get(classPathFileBak.getAbsolutePath()), StandardCopyOption.REPLACE_EXISTING);
		}
		catch (IOException e) {
			// can't back up file but we should continue anyway
			Activator.log("Failed to backup classfile [" + classPathFile.getAbsolutePath() + "]");
		}
	}
	javaProject.setRawClasspath(classpath, monitor);	
}
 
源代码13 项目: lrkFM   文件: OperationUtil.java
private static boolean doCopyNoValidation(FMFile f, File d) throws BlockingStuffOnMainThreadException {
    if(Looper.myLooper() == Looper.getMainLooper()) {
        throw new BlockingStuffOnMainThreadException();
    }
    try {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Files.copy(f.getFile().toPath(), d.toPath(), StandardCopyOption.REPLACE_EXISTING);
        } else {
            if (f.getFile().isDirectory()) {
                copyDirectory(f.getFile(), d);
            } else {
                copyFile(f.getFile(), d);
            }
        }
        return true;
    } catch (IOException e) {
        Log.e(TAG, "Unable to copy file!", e);
        return false;
    }
}
 
源代码14 项目: jdk8u60   文件: ProcessAttachDebuggee.java
public static void main(String args[]) throws Exception {
    // bind to a random port
    ServerSocket ss = new ServerSocket(0);
    int port = ss.getLocalPort();

    // Write the port number to the given file
    File partial = new File(args[0] + ".partial");
    File portFile = new File(args[0]);
    try (FileOutputStream fos = new FileOutputStream(partial)) {
        fos.write( Integer.toString(port).getBytes("UTF-8") );
    }
    Files.move(partial.toPath(), portFile.toPath(), StandardCopyOption.ATOMIC_MOVE);

    System.out.println("Debuggee bound to port: " + port);
    System.out.flush();

    // wait for test harness to connect
    Socket s = ss.accept();
    s.close();
    ss.close();

    System.out.println("Debuggee shutdown.");
}
 
@Override
public void store(MultipartFile file) {
    String filename = StringUtils.cleanPath(file.getOriginalFilename());
    try {
        if (file.isEmpty()) {
            throw new StorageException("Failed to store empty file " + filename);
        }
        if (filename.contains("..")) {
            // This is a security check
            throw new StorageException(
                "Cannot store file with relative path outside current directory " + filename);
        }
        try (InputStream inputStream = file.getInputStream()) {
            Files.copy(inputStream, this.rootLocation.resolve(filename), StandardCopyOption.REPLACE_EXISTING);
        }
    } catch (IOException e) {
        throw new StorageException("Failed to store file " + filename, e);
    }
}
 
源代码16 项目: wildwebdeveloper   文件: Utils.java
/**
 * Provisions a project that's part of the "testProjects"
 * @param folderName the folderName under "testProjects" to provision from
 * @return the provisioned project
 * @throws CoreException
 * @throws IOException
 */
public static IProject provisionTestProject(String folderName) throws CoreException, IOException {
	URL url = FileLocator.find(Platform.getBundle("org.eclipse.wildwebdeveloper.tests"),
			Path.fromPortableString("testProjects/" + folderName), null);
	url = FileLocator.toFileURL(url);
	File folder = new File(url.getFile());
	if (folder.exists()) {
		IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject("testProject" + System.nanoTime());
		project.create(null);
		project.open(null);
		java.nio.file.Path sourceFolder = folder.toPath();
		java.nio.file.Path destFolder = project.getLocation().toFile().toPath();

		Files.walk(sourceFolder).forEach(source -> {
			try {
				Files.copy(source, destFolder.resolve(sourceFolder.relativize(source)), StandardCopyOption.REPLACE_EXISTING);
			} catch (IOException e) {
				e.printStackTrace();
			}
		});
		project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
		return project;
	}
	return null;
}
 
源代码17 项目: code-examples   文件: FileSystemStorageService.java
@Override
public String store(MultipartFile file) {
    String filename = StringUtils.cleanPath(file.getOriginalFilename());
    try {
        if (file.isEmpty()) {
            throw new StorageException("Failed to store empty file " + filename);
        }
        if (filename.contains("..")) {
            // This is a security check
            throw new StorageException(
                    "Cannot store file with relative path outside current directory "
                            + filename);
        }
        try (InputStream inputStream = file.getInputStream()) {
            Files.copy(inputStream, this.rootLocation.resolve(filename),
                    StandardCopyOption.REPLACE_EXISTING);
        }
    }
    catch (IOException e) {
        throw new StorageException("Failed to store file " + filename, e);
    }

    return filename;
}
 
源代码18 项目: evosql   文件: CategorizedQueryCollector.java
void open() throws IOException {
	outputs = new PrintStream[SYSTEMS];
	String scenarioPath = Paths.get(System.getProperty("user.dir")).toString() + "/scenarios/";
	// For each system, 
	for (int i = 0; i < SYSTEMS; i++) {
		String path = scenarioPath + systemFolders[i] + "-sampled/";
		// rename queries.sql if it exists
		if (Files.exists(Paths.get(path + "queries.sql"))) {
			Files.move(Paths.get(path + "queries.sql")
					, Paths.get(path + "queries-" + timeStampPattern.format(java.time.LocalDateTime.now()) + ".sql")
					, StandardCopyOption.REPLACE_EXISTING);
		}
		
		// Create new queries.sql
		outputs[i] = new PrintStream(path + "queries.sql");
	}
}
 
源代码19 项目: rpi-ws281x-java   文件: Ws281xLedStrip.java
private static void initializeNative() {
    synchronized ( loaded ) {
        if ( !loaded.get() ) {
            try {
                Path path = Files.createTempFile( "lib" + LIB_NAME, ".so" );
                path.toFile().deleteOnExit();
                Files.copy( Ws281xLedStrip.class.getResourceAsStream( "/lib" + LIB_NAME + ".so" ), path,
                        StandardCopyOption.REPLACE_EXISTING );
                System.load( path.toString() );
                loaded.set( true );
                LOG.info("Native library loaded");
            } catch ( IOException e ) {
                LOG.error( "Error loading library from classpath: ", e );

                // Try load the usual way...
                System.loadLibrary( LIB_NAME );
                loaded.set( true );
                LOG.info("Native library loaded");
            }
        }
    }
}
 
源代码20 项目: openjdk-8-source   文件: ProcessAttachDebuggee.java
public static void main(String args[]) throws Exception {
    // bind to a random port
    ServerSocket ss = new ServerSocket(0);
    int port = ss.getLocalPort();

    // Write the port number to the given file
    File partial = new File(args[0] + ".partial");
    File portFile = new File(args[0]);
    try (FileOutputStream fos = new FileOutputStream(partial)) {
        fos.write( Integer.toString(port).getBytes("UTF-8") );
    }
    Files.move(partial.toPath(), portFile.toPath(), StandardCopyOption.ATOMIC_MOVE);

    System.out.println("Debuggee bound to port: " + port);
    System.out.flush();

    // wait for test harness to connect
    Socket s = ss.accept();
    s.close();
    ss.close();

    System.out.println("Debuggee shutdown.");
}
 
private void copyProfileFile(Path source, Path destPath, String errorTitle) {
    Path destFile = destPath.resolve(source.getFileName());
    if (destFile.toFile().exists()) {
        boolean overwrite = MessageDialog.openConfirm(getShell(),
                Messages.TraceControl_ProfileAlreadyExists,
                NLS.bind(Messages.TraceControl_OverwriteQuery, destFile.getFileName()));

        if (!overwrite) {
            return;
        }
    }
    try {
        Files.copy(source, destFile, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e1) {
        MessageDialog.openError(getShell(),
                errorTitle,
                "Error copying profile:\n" + e1.toString()); //$NON-NLS-1$
    }
}
 
源代码22 项目: openjdk-8   文件: ReplayCacheTestProc.java
private static Ex round(int i, int old, int server, boolean expected)
        throws Exception {
    ps[server].println("TEST");
    ps[server].println(reqs.get(old).msg);
    String reply = ps[server].readData();
    Ex result = new Ex();
    result.i = i;
    result.expected = expected;
    result.server = ps[server].debug();
    result.actual = Boolean.valueOf(reply);
    result.user = reqs.get(old).user;
    result.peer = reqs.get(old).peer;
    result.old = old;
    result.csize = csize(result.peer);
    result.hash = hash(reqs.get(old).msg);
    if (new File(dfl(result.peer)).exists()) {
        Files.copy(Paths.get(dfl(result.peer)), Paths.get(
            String.format("%03d-USER%d-host%d-%s-%s",
                i, result.user, result.peer, result.server,
                result.actual)
            + "-" + result.hash),
            StandardCopyOption.COPY_ATTRIBUTES);
    }
    return result;
}
 
源代码23 项目: jdk8u60   文件: ClassFileInstaller.java
/**
 * @param args The names of the classes to dump
 * @throws Exception
 */
public static void main(String... args) throws Exception {
    for (String arg : args) {
        ClassLoader cl = ClassFileInstaller.class.getClassLoader();

        // Convert dotted class name to a path to a class file
        String pathName = arg.replace('.', '/').concat(".class");
        InputStream is = cl.getResourceAsStream(pathName);

        // Create the class file's package directory
        Path p = Paths.get(pathName);
        if (pathName.contains("/")) {
            Files.createDirectories(p.getParent());
        }
        // Create the class file
        Files.copy(is, p, StandardCopyOption.REPLACE_EXISTING);
    }
}
 
源代码24 项目: jdk8u-dev-jdk   文件: ReplayCacheTestProc.java
private static Ex round(int i, int old, int server, boolean expected)
        throws Exception {
    ps[server].println("TEST");
    ps[server].println(reqs.get(old).msg);
    String reply = ps[server].readData();
    Ex result = new Ex();
    result.i = i;
    result.expected = expected;
    result.server = ps[server].debug();
    result.actual = Boolean.valueOf(reply);
    result.user = reqs.get(old).user;
    result.peer = reqs.get(old).peer;
    result.old = old;
    result.csize = csize(result.peer);
    result.hash = hash(reqs.get(old).msg);
    if (new File(dfl(result.peer)).exists()) {
        Files.copy(Paths.get(dfl(result.peer)), Paths.get(
            String.format("%03d-USER%d-host%d-%s-%s",
                i, result.user, result.peer, result.server,
                result.actual)
            + "-" + result.hash),
            StandardCopyOption.COPY_ATTRIBUTES);
    }
    return result;
}
 
源代码25 项目: hop   文件: UIGit.java
@Override
public void add( String filepattern ) {
  try {
    if ( filepattern.endsWith( ".ours" ) || filepattern.endsWith( ".theirs" ) ) {
      FileUtils.rename( new File( directory, filepattern ),
          new File( directory, FilenameUtils.removeExtension( filepattern ) ),
          StandardCopyOption.REPLACE_EXISTING );
      filepattern = FilenameUtils.removeExtension( filepattern );
      org.apache.commons.io.FileUtils.deleteQuietly( new File( directory, filepattern + ".ours" ) );
      org.apache.commons.io.FileUtils.deleteQuietly( new File( directory, filepattern + ".theirs" ) );
    }
    git.add().addFilepattern( filepattern ).call();
  } catch ( Exception e ) {
    showMessageBox( BaseMessages.getString( PKG, "Dialog.Error" ), e.getMessage() );
  }
}
 
源代码26 项目: I18nUpdateMod   文件: ResourcePackBuilder.java
private void copyResourcePack() {
    assetFolder.mkdirs();
    // PNG 图标
    File icon = new File(rootPath, "pack.png");
    if (!icon.exists()) {
        ClassLoader classLoader = this.getClass().getClassLoader();
        InputStream in = classLoader.getResourceAsStream("assets/i18nmod/icon/pack.png");

        try {
            Files.copy(in, icon.toPath(), StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            logger.error("Error while copying icon file:", e);
        }
    }
    // pack.mcmeta
    writePackMeta();
}
 
源代码27 项目: smithy   文件: DefaultFileManifest.java
@Override
public Path writeFile(Path path, InputStream fileContentsInputStream) {
    path = addFile(path);

    try {
        Files.copy(fileContentsInputStream, path, StandardCopyOption.REPLACE_EXISTING);
        return path;
    } catch (IOException e) {
        throw new SmithyBuildException("Unable to write contents of file `" + path + "`: " + e.getMessage(), e);
    }
}
 
源代码28 项目: activemq-artemis   文件: ArtemisCreatePlugin.java
private void copyToDir(String destination, File projectLib, PrintStream commandLineStream) throws IOException {
   Path target = instance.toPath().resolve(destination).resolve(projectLib.getName());
   File file = target.toFile();
   File parent = file.getParentFile();
   if (!parent.exists()) {
      parent.mkdirs();
      commandLineStream.println("mkdir " + file.getParent());
   }

   commandLineStream.println("cp " + projectLib.getAbsolutePath() + " " + target);
   getLog().debug("Copying " + projectLib.getName() + " as " + target.toFile().getAbsolutePath());
   Files.copy(projectLib.toPath(), target, StandardCopyOption.REPLACE_EXISTING);
}
 
源代码29 项目: Angelia-core   文件: YAMLFileConfig.java
private boolean writeFile(InputStream source, Path dest) {
	try {
		dest.getParent().toFile().mkdirs();
		dest.toFile().createNewFile();
		Files.copy(source, dest, StandardCopyOption.REPLACE_EXISTING);
		return true;
	} catch (IOException ex) {
		logger.warn("Failed to save default config, most likely we don't have write perms or the disk is full", ex);
		return false;
	}
}
 
源代码30 项目: Box   文件: ResourcesSaver.java
private void saveResourceFile(ResourceFile resFile, File outFile) throws JadxException {
	ResourcesLoader.decodeStream(resFile, (size, is) -> {
		try {
			Files.copy(is, outFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
		} catch (Exception e) {
			throw new JadxRuntimeException("Resource file save error", e);
		}
		return null;
	});
}