下面列出了java.io.SyncFailedException#java.nio.file.StandardCopyOption 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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);
}
}
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;
}
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;
}
@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);
}
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);
}
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);
}
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.");
}
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;
}
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;
}
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);
}
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;
}
}
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);
}
}
/**
* 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;
}
@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;
}
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");
}
}
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");
}
}
}
}
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$
}
}
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;
}
/**
* @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);
}
}
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;
}
@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() );
}
}
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();
}
@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);
}
}
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);
}
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;
}
}
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;
});
}