List of usage examples for java.nio.file StandardCopyOption REPLACE_EXISTING
StandardCopyOption REPLACE_EXISTING
To view the source code for java.nio.file StandardCopyOption REPLACE_EXISTING.
Click Source Link
From source file:ufjf.dcc.faces.controller.IndividuoController.java
public void upload(FileUploadEvent e) { try {//from w w w . j a v a 2 s . co m // Get uploaded file from the FileUploadEvent this.file = e.getFile(); // Print out the information of the file System.out.println("Uploaded File Name Is :: " + file.getFileName() + " :: Uploaded File Size :: " + file.getSize()); //atualiza nome do arquivo //Path folder = Paths.get(this.DIRETORIO_FOTOS); String filename = UUID.randomUUID().toString(); String extension = FilenameUtils.getExtension(file.getFileName()); this.individuo.setFoto(filename + "." + extension); //Path filePath = Files.createTempFile(folder, filename, "." + extension); Path filePath = Paths.get(this.DIRETORIO_FOTOS + filename + "." + extension); //salva arquivo try (InputStream input = this.file.getInputstream()) { Files.copy(input, filePath, StandardCopyOption.REPLACE_EXISTING); } System.out.println("Uploaded file successfully saved in " + file); System.out.println("Uploaded file successfully saved in " + this.individuo.getFoto()); FacesContext context = FacesContext.getCurrentInstance(); context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Sucesso", "Foto carregada com sucesso!")); } catch (IOException ex) { Logger.getLogger(IndividuoController.class.getName()).log(Level.SEVERE, null, ex); FacesContext context = FacesContext.getCurrentInstance(); context.addMessage(null, new FacesMessage("Exception", ex.getMessage())); } }
From source file:com.google.devtools.build.lib.bazel.repository.TarGzFunction.java
@Nullable @Override/* ww w. j a va 2s . co m*/ public SkyValue compute(SkyKey skyKey, Environment env) throws RepositoryFunctionException { DecompressorDescriptor descriptor = (DecompressorDescriptor) skyKey.argument(); Optional<String> prefix = descriptor.prefix(); boolean foundPrefix = false; try (GZIPInputStream gzipStream = new GZIPInputStream( new FileInputStream(descriptor.archivePath().getPathFile()))) { TarArchiveInputStream tarStream = new TarArchiveInputStream(gzipStream); TarArchiveEntry entry; while ((entry = tarStream.getNextTarEntry()) != null) { StripPrefixedPath entryPath = StripPrefixedPath.maybeDeprefix(entry.getName(), prefix); foundPrefix = foundPrefix || entryPath.foundPrefix(); if (entryPath.skip()) { continue; } Path filename = descriptor.repositoryPath().getRelative(entryPath.getPathFragment()); FileSystemUtils.createDirectoryAndParents(filename.getParentDirectory()); if (entry.isDirectory()) { FileSystemUtils.createDirectoryAndParents(filename); } else { if (entry.isSymbolicLink()) { PathFragment linkName = new PathFragment(entry.getLinkName()); if (linkName.isAbsolute()) { linkName = linkName.relativeTo(PathFragment.ROOT_DIR); linkName = descriptor.repositoryPath().getRelative(linkName).asFragment(); } FileSystemUtils.ensureSymbolicLink(filename, linkName); } else { Files.copy(tarStream, filename.getPathFile().toPath(), StandardCopyOption.REPLACE_EXISTING); filename.chmod(entry.getMode()); } } } } catch (IOException e) { throw new RepositoryFunctionException(e, Transience.TRANSIENT); } if (prefix.isPresent() && !foundPrefix) { throw new RepositoryFunctionException( new IOException("Prefix " + prefix.get() + " was given, but not found in the archive"), Transience.PERSISTENT); } return new DecompressorValue(descriptor.repositoryPath()); }
From source file:org.roda.core.storage.fs.FSUtils.java
/** * Method that safely updates a file, given an inputstream, by copying the * content of the stream to a temporary file which then gets moved into the * final location (doing an atomic move). </br> * </br>// w w w. ja v a 2 s .c o m * In theory (as it depends on the file system implementation), this method is * useful for ensuring thread safety. </br> * </br> * NOTE: the stream is closed in the end. * * @param stream * stream with the content to be updated * @param toPath * location of the file being updated * * @throws IOException * if an error occurs while copying/moving * */ public static void safeUpdate(InputStream stream, Path toPath) throws IOException { try { Path tempToPath = toPath.getParent() .resolve(toPath.getFileName().toString() + ".temp" + System.nanoTime()); Files.copy(stream, tempToPath); Files.move(tempToPath, toPath, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); } finally { IOUtils.closeQuietly(stream); } }
From source file:io.druid.indexer.HdfsClasspathSetupTest.java
@Before public void setUp() throws IOException { // intermedatePath and finalClasspath are relative to hdfsTmpDir directory. intermediatePath = new Path(String.format("/tmp/classpath/%s", UUIDUtils.generateUuid())); finalClasspath = new Path(String.format("/tmp/intermediate/%s", UUIDUtils.generateUuid())); dummyJarFile = tempFolder.newFile("dummy-test.jar"); Files.copy(new ByteArrayInputStream(StringUtils.toUtf8(dummyJarString)), dummyJarFile.toPath(), StandardCopyOption.REPLACE_EXISTING); }
From source file:org.lamport.tla.toolbox.jcloud.PayloadHelper.java
public static Payload appendModel2Jar(final Path modelPath, String mainClass, Properties properties, IProgressMonitor monitor) throws IOException { /*/* w w w. j av a 2s. co m*/ * Get the standard tla2tools.jar from the classpath as a blueprint. * It's located in the org.lamport.tla.toolbox.jclouds bundle in the * files/ directory. It uses OSGi functionality to read files/tla2tools.jar * from the .jclouds bundle. * The copy of the blueprint will contain the spec & model and * additional metadata (properties, amended manifest). */ final Bundle bundle = FrameworkUtil.getBundle(PayloadHelper.class); final URL toolsURL = bundle.getEntry("files/tla2tools.jar"); if (toolsURL == null) { throw new RuntimeException("No tlatools.jar and/or spec to deploy"); } /* * Copy the tla2tools.jar blueprint to a temporary location on * disk to append model files below. */ final File tempFile = File.createTempFile("tla2tools", ".jar"); tempFile.deleteOnExit(); try (FileOutputStream out = new FileOutputStream(tempFile)) { IOUtils.copy(toolsURL.openStream(), out); } /* * Create a virtual filesystem in jar format. */ final Map<String, String> env = new HashMap<>(); env.put("create", "true"); final URI uri = URI.create("jar:" + tempFile.toURI()); try (FileSystem fs = FileSystems.newFileSystem(uri, env)) { /* * Copy the spec and model into the jar's model/ folder. * Also copy any module override (.class file) into the jar. */ try (DirectoryStream<Path> modelDirectoryStream = Files.newDirectoryStream(modelPath, "*.{cfg,tla,class}")) { for (final Path file : modelDirectoryStream) { final Path to = fs.getPath("/model/" + file.getFileName()); Files.copy(file, to, StandardCopyOption.REPLACE_EXISTING); } } /* * Add given class as Main-Class statement to jar's manifest. This * causes Java to launch this class when no other Main class is * given on the command line. Thus, it shortens the command line * for us. */ final Path manifestPath = fs.getPath("/META-INF/", "MANIFEST.MF"); final Manifest manifest = new Manifest(Files.newInputStream(manifestPath)); manifest.getMainAttributes().put(Attributes.Name.MAIN_CLASS, mainClass); final PipedOutputStream ps = new PipedOutputStream(); final PipedInputStream is = new PipedInputStream(ps); manifest.write(ps); ps.close(); Files.copy(is, manifestPath, StandardCopyOption.REPLACE_EXISTING); /* * Add properties file to archive. The property file contains the * result email address... from where TLC eventually reads it. */ // On Windows 7 and above the file has to be created in the system's // temp folder. Otherwise except file creation to fail with a // AccessDeniedException final File f = File.createTempFile("generated", "properties"); OutputStream out = new FileOutputStream(f); // Append all entries in "properties" to the temp file f properties.store(out, "This is an optional header comment string"); // Copy the temp file f into the jar with path /model/generated.properties. final Path to = fs.getPath("/model/generated.properties"); Files.copy(f.toPath(), to, StandardCopyOption.REPLACE_EXISTING); } catch (final IOException e1) { throw new RuntimeException("No model directory found to deploy", e1); } /* * Compress archive with pack200 to achieve a much higher compression rate. We * are going to send the file on the wire after all: * * effort: take more time choosing codings for better compression segment: use * largest-possible archive segments (>10% better compression) mod time: smear * modification times to a single value deflate: ignore all JAR deflation hints * in original archive */ final Packer packer = Pack200.newPacker(); final Map<String, String> p = packer.properties(); p.put(Packer.EFFORT, "9"); p.put(Packer.SEGMENT_LIMIT, "-1"); p.put(Packer.MODIFICATION_TIME, Packer.LATEST); p.put(Packer.DEFLATE_HINT, Packer.FALSE); // Do not reorder which changes package names. Pkg name changes e.g. break // SimpleFilenameToStream. p.put(Packer.KEEP_FILE_ORDER, Packer.TRUE); // Throw an error if any of the above attributes is unrecognized. p.put(Packer.UNKNOWN_ATTRIBUTE, Packer.ERROR); final File packTempFile = File.createTempFile("tla2tools", ".pack.gz"); try (final JarFile jarFile = new JarFile(tempFile); final GZIPOutputStream fos = new GZIPOutputStream(new FileOutputStream(packTempFile));) { packer.pack(jarFile, fos); } catch (IOException ioe) { throw new RuntimeException("Failed to pack200 the tla2tools.jar file", ioe); } /* * Convert the customized tla2tools.jar into a jClouds payload object. This is * the format it will be transfered on the wire. This is handled by jClouds * though. */ Payload jarPayLoad = null; try { final InputStream openStream = new FileInputStream(packTempFile); jarPayLoad = Payloads.newInputStreamPayload(openStream); // manually set length of content to prevent a NPE bug jarPayLoad.getContentMetadata().setContentLength(Long.valueOf(openStream.available())); } catch (final IOException e1) { throw new RuntimeException("No tlatools.jar to deploy", e1); } finally { monitor.worked(5); } return jarPayLoad; }
From source file:org.ballerinalang.stdlib.system.FileSystemTest.java
@Test(description = "Test for changing file path") public void testFileRename() throws IOException { try {/* ww w . j av a 2 s . co m*/ Files.copy(srcFilePath, tempSourcePath, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); BValue[] args = { new BString(tempSourcePath.toString()), new BString(tempDestPath.toString()) }; BRunUtil.invoke(compileResult, "testRename", args); Assert.assertTrue(Files.exists(tempDestPath)); assertFalse(Files.exists(tempSourcePath)); } finally { Files.deleteIfExists(tempSourcePath); Files.deleteIfExists(tempDestPath); } }
From source file:com.castlemock.web.basis.manager.FileManager.java
public List<File> uploadFiles(final String downloadURL) throws IOException { final File fileDirectory = new File(tempFilesFolder); if (!fileDirectory.exists()) { fileDirectory.mkdirs();// w ww. j a va2 s. co m } final URL url = new URL(downloadURL); final String fileName = generateNewFileName(); final File file = new File(fileDirectory.getAbsolutePath() + File.separator + fileName); if (!file.exists()) { file.createNewFile(); } final Path targetPath = file.toPath(); Files.copy(url.openStream(), targetPath, StandardCopyOption.REPLACE_EXISTING); final List<File> files = new ArrayList<>(); files.add(file); return files; }
From source file:org.opencb.opencga.storage.core.variant.VariantStorageBaseTest.java
@BeforeClass public static void _beforeClass() throws Exception { // System.setProperty(org.slf4j.impl.SimpleLogger.DEFAULT_LOG_LEVEL_KEY, "debug"); newRootDir();//w w w .j a v a 2 s.c om if (rootDir.toFile().exists()) { IOUtils.deleteDirectory(rootDir); Files.createDirectories(rootDir); } Path inputPath = rootDir.resolve(VCF_TEST_FILE_NAME); Path smallInputPath = rootDir.resolve(SMALL_VCF_TEST_FILE_NAME); Path corruptedInputPath = rootDir.resolve(VCF_CORRUPTED_FILE_NAME); Files.copy(VariantStorageManagerTest.class.getClassLoader().getResourceAsStream(VCF_TEST_FILE_NAME), inputPath, StandardCopyOption.REPLACE_EXISTING); Files.copy(VariantStorageManagerTest.class.getClassLoader().getResourceAsStream(SMALL_VCF_TEST_FILE_NAME), smallInputPath, StandardCopyOption.REPLACE_EXISTING); Files.copy(VariantStorageManagerTest.class.getClassLoader().getResourceAsStream(VCF_CORRUPTED_FILE_NAME), corruptedInputPath, StandardCopyOption.REPLACE_EXISTING); inputUri = inputPath.toUri(); smallInputUri = smallInputPath.toUri(); corruptedInputUri = corruptedInputPath.toUri(); outputUri = rootDir.toUri(); // logger.info("count: " + count.getAndIncrement()); }
From source file:org.apache.druid.indexer.HdfsClasspathSetupTest.java
@Before public void setUp() throws IOException { // intermedatePath and finalClasspath are relative to hdfsTmpDir directory. intermediatePath = new Path(StringUtils.format("/tmp/classpath/%s", UUIDUtils.generateUuid())); finalClasspath = new Path(StringUtils.format("/tmp/intermediate/%s", UUIDUtils.generateUuid())); dummyJarFile = tempFolder.newFile("dummy-test.jar"); Files.copy(new ByteArrayInputStream(StringUtils.toUtf8(dummyJarString)), dummyJarFile.toPath(), StandardCopyOption.REPLACE_EXISTING); }
From source file:es.ucm.fdi.storage.business.entity.StorageObject.java
public void save(InputStream input) throws IOException { Path file = root.resolve(UUID.randomUUID().toString()); try (FileOutputStream out = new FileOutputStream(file.toFile())) { MessageDigest sha2sum = MessageDigest.getInstance("SHA-256"); byte[] dataBytes = new byte[4 * 1024]; int nread = 0; long length = 0; while ((nread = input.read(dataBytes)) != -1) { sha2sum.update(dataBytes, 0, nread); out.write(dataBytes, 0, nread); length += nread;// w ww . j a va2 s.c o m } this.internalName = toHexString(sha2sum.digest()); this.length = length; out.close(); String folder = internalName.substring(0, 2); Path parent = Files.createDirectories(root.resolve(folder)); Files.move(file, parent.resolve(internalName), StandardCopyOption.REPLACE_EXISTING); } catch (NoSuchAlgorithmException nsae) { throw new IOException("Cant save file", nsae); } }