List of usage examples for java.nio.file StandardOpenOption WRITE
StandardOpenOption WRITE
To view the source code for java.nio.file StandardOpenOption WRITE.
Click Source Link
From source file:com.codealot.textstore.FileStore.java
@Override public String storeText(final Reader reader) throws IOException { Objects.requireNonNull(reader, "No reader provided"); // make the digester final MessageDigest digester = getDigester(); // make temp file final Path textPath = Paths.get(this.storeRoot, UUID.randomUUID().toString()); // stream to file, building digest final ReaderInputStream readerAsBytes = new ReaderInputStream(reader, StandardCharsets.UTF_8); try {/*from ww w.j a v a2s. com*/ final byte[] bytes = new byte[1024]; int readLength = 0; long totalRead = 0L; while ((readLength = readerAsBytes.read(bytes)) > 0) { totalRead += readLength; digester.update(bytes, 0, readLength); final byte[] readBytes = Arrays.copyOf(bytes, readLength); Files.write(textPath, readBytes, StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.APPEND); } // check that something was read if (totalRead == 0L) { return this.storeText(""); } // make the hash final String hash = byteToHex(digester.digest()); // store the text, if new final Path finalPath = Paths.get(this.storeRoot, hash); if (Files.exists(finalPath)) { // already existed, so delete uuid named one Files.deleteIfExists(textPath); } else { // rename the file Files.move(textPath, finalPath); } return hash; } finally { if (readerAsBytes != null) { readerAsBytes.close(); } } }
From source file:org.basinmc.maven.plugins.minecraft.AbstractArtifactMojo.java
/** * Fetches any resources from a remote HTTP server and stores it in a specified file. *//*from w w w .j a va 2 s . c o m*/ protected void fetch(@Nonnull URI uri, @Nonnull Path target) throws IOException { this.fetch(uri, FileChannel.open(target, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)); }
From source file:org.darkware.wpman.security.ChecksumDatabase.java
/** * Write the database to the attached file path. This path is declared in the constructor and cannot be * changed./*from w w w. j ava 2s.c om*/ */ public void writeDatabase() { this.lock.writeLock().lock(); try { ChecksumDatabase.log.info("Writing integrity database: {}", this.dbFile); try (BufferedWriter db = Files.newBufferedWriter(this.dbFile, StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING)) { for (Map.Entry<Path, String> entry : this.hashes.entrySet()) { db.write(entry.getKey().toString()); db.write(":"); db.write(entry.getValue()); db.newLine(); } } catch (IOException e) { ChecksumDatabase.log.error("Error while writing integrity database: {}", e.getLocalizedMessage(), e); } } finally { this.lock.writeLock().unlock(); } }
From source file:org.cyclop.service.common.FileStorage.java
private FileChannel openForWrite(Path histPath) throws IOException { FileChannel byteChannel = FileChannel.open(histPath, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE); byteChannel.force(true);//from ww w .jav a 2s.c o m FileChannel lockChannel = lock(histPath, byteChannel); return lockChannel; }
From source file:com.github.jinahya.simple.file.back.LocalFileBackTest.java
@Test(enabled = true, invocationCount = 1) public void delete() throws IOException, FileBackException { fileContext.fileOperationSupplier(() -> FileOperation.DELETE); final ByteBuffer fileKey = randomFileKey(); if (current().nextBoolean()) { fileContext.sourceKeySupplier(() -> fileKey); } else {/*from w ww . j a v a2 s. c om*/ fileContext.targetKeySupplier(() -> fileKey); } final Path leafPath = LocalFileBack.leafPath(rootPath, fileKey, true); final byte[] fileBytes = randomFileBytes(); final boolean fileWritten = Files.isRegularFile(leafPath) || current().nextBoolean(); if (fileWritten) { Files.write(leafPath, fileBytes, StandardOpenOption.CREATE, StandardOpenOption.WRITE); logger.trace("file written"); } fileBack.operate(fileContext); }
From source file:org.dmb.trueprice.utils.internal.FileUtils.java
/** * Write FID's attachements on server * /*from w w w . ja v a 2 s . c om*/ * @param fileName - Nom du fichier joint * @param fileContent - InputStream contenant le coprs du fichier * @param targetFolder - Dossier o crire le fichier */ // public static void writeFile(String fileName,InputStream fileContent, String targetFolder) throws IOException{ public static void writeFile(String fileName, byte[] bytes, String targetFolder) throws IOException { // try { Files.write(Paths.get(targetFolder + File.separator + fileName), bytes, StandardOpenOption.WRITE // , StandardOpenOption.CREATE_NEW ); // } catch ( e) { // logger.error("IOException writing attachment on disk : " + e.getMessage()); // } }
From source file:com.evolveum.midpoint.model.intest.manual.CsvBackingStore.java
protected void replaceInCsv(String[] data) throws IOException { List<String> lines = Files.readAllLines(Paths.get(CSV_TARGET_FILE.getPath())); boolean found = false; for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); String[] cols = line.split(","); if (cols[0].matches("\"" + data[0] + "\"")) { lines.set(i, formatCsvLine(data)); found = true;//w ww . j av a 2s. c om } } if (!found) { throw new IllegalStateException("Not found in CSV: " + data[0]); } Files.write(Paths.get(CSV_TARGET_FILE.getPath()), lines, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); }
From source file:org.cyclop.service.common.FileStorage.java
private FileChannel openForRead(Path histPath) throws IOException { File file = histPath.toFile(); if (!file.exists() || !file.canRead()) { LOG.debug("History file not found: " + histPath); return null; }/* w ww . j a v a 2s .c om*/ FileChannel byteChannel = FileChannel.open(histPath, StandardOpenOption.READ, StandardOpenOption.WRITE); FileChannel lockChannel = lock(histPath, byteChannel); return lockChannel; }
From source file:com.databasepreservation.visualization.utils.SolrUtils.java
public static void setupSolrCloudConfigsets(String zkHost) { // before anything else, try to get a zookeeper client CloudSolrClient zkClient = new CloudSolrClient(zkHost); // get resources and copy them to a temporary directory Path databaseDir = null;/* w w w.j a va 2 s.c o m*/ Path tableDir = null; Path savedSearchesDir = null; try { final File jarFile = new File( SolrManager.class.getProtectionDomain().getCodeSource().getLocation().toURI()); // if it is a directory the application in being run from an IDE // in that case do not setup (assuming setup is done) if (!jarFile.isDirectory()) { databaseDir = Files.createTempDirectory("dbv_db_"); tableDir = Files.createTempDirectory("dbv_tab_"); savedSearchesDir = Files.createTempDirectory("dbv_tab_"); final JarFile jar = new JarFile(jarFile); final Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String name = entry.getName(); String nameWithoutOriginPart = null; Path destination = null; if (name.startsWith(ViewerSafeConstants.SOLR_CONFIGSET_DATABASE_RESOURCE + "/")) { nameWithoutOriginPart = name .substring(ViewerSafeConstants.SOLR_CONFIGSET_DATABASE_RESOURCE.length() + 1); destination = databaseDir; } else if (name.startsWith(ViewerSafeConstants.SOLR_CONFIGSET_TABLE_RESOURCE + "/")) { nameWithoutOriginPart = name .substring(ViewerSafeConstants.SOLR_CONFIGSET_TABLE_RESOURCE.length() + 1); destination = tableDir; } else if (name.startsWith(ViewerSafeConstants.SOLR_CONFIGSET_SEARCHES_RESOURCE + "/")) { nameWithoutOriginPart = name .substring(ViewerSafeConstants.SOLR_CONFIGSET_SEARCHES_RESOURCE.length() + 1); destination = savedSearchesDir; } else { continue; } Path output = destination.resolve(nameWithoutOriginPart); if (name.endsWith("/")) { Files.createDirectories(output); } else { InputStream inputStream = SolrManager.class.getResourceAsStream("/" + name); output = Files.createFile(output); OutputStream outputStream = Files.newOutputStream(output, StandardOpenOption.CREATE, StandardOpenOption.WRITE); IOUtils.copy(inputStream, outputStream); inputStream.close(); outputStream.close(); } } jar.close(); } } catch (IOException | URISyntaxException e) { LOGGER.error("Could not extract Solr configset", e); if (databaseDir != null) { try { FileUtils.deleteDirectoryRecursive(databaseDir); } catch (IOException e1) { LOGGER.debug("IO error deleting temporary folder: " + databaseDir, e1); } } if (tableDir != null) { try { FileUtils.deleteDirectoryRecursive(tableDir); } catch (IOException e1) { LOGGER.debug("IO error deleting temporary folder: " + tableDir, e1); } } databaseDir = null; tableDir = null; } // copy configurations to solr if (databaseDir != null && tableDir != null) { try { zkClient.uploadConfig(databaseDir, ViewerSafeConstants.SOLR_CONFIGSET_DATABASE); } catch (IOException e) { LOGGER.debug("IO error uploading database config to solr cloud", e); } try { zkClient.uploadConfig(tableDir, ViewerSafeConstants.SOLR_CONFIGSET_TABLE); } catch (IOException e) { LOGGER.debug("IO error uploading table config to solr cloud", e); } try { zkClient.uploadConfig(savedSearchesDir, ViewerSafeConstants.SOLR_CONFIGSET_SEARCHES); } catch (IOException e) { LOGGER.debug("IO error uploading saved searches config to solr cloud", e); } try { FileUtils.deleteDirectoryRecursive(databaseDir); } catch (IOException e1) { LOGGER.debug("IO error deleting temporary folder: " + databaseDir, e1); } try { FileUtils.deleteDirectoryRecursive(tableDir); } catch (IOException e1) { LOGGER.debug("IO error deleting temporary folder: " + tableDir, e1); } try { FileUtils.deleteDirectoryRecursive(savedSearchesDir); } catch (IOException e1) { LOGGER.debug("IO error deleting temporary folder: " + savedSearchesDir, e1); } } try { zkClient.close(); } catch (IOException e) { LOGGER.debug("IO error closing connection to solr cloud", e); } }
From source file:it.greenvulcano.configuration.BaseConfigurationManager.java
@Override public synchronized void saveXMLConfigProperties(Properties xmlConfigProperties) throws IOException { if (xmlConfigProperties != null) { try (OutputStream xmlConfigPropertiesOutputStream = Files.newOutputStream( Paths.get(XMLConfig.getBaseConfigPath(), "XMLConfig.properties"), StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) { xmlConfigProperties.store(xmlConfigPropertiesOutputStream, null); }/* w ww. jav a 2s . c o m*/ } }