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:org.kalypso.grid.BinaryGeoGrid.java
/** * Crates a new grid file with the given size and scale.<br> * The grid is then opened in write mode, so its values can then be set.<br> * The grid must be disposed afterwards in order to flush the written information. * * //from ww w . java2 s. co m * @param fillGrid * If set to <code>true</code>, the grid will be initially filled with no-data values. Else, the grid values * are undetermined. */ public static BinaryGeoGrid createGrid(final File file, final int sizeX, final int sizeY, final int scale, final Coordinate origin, final Coordinate offsetX, final Coordinate offsetY, final String sourceCRS, final boolean fillGrid) throws GeoGridException { try { final FileChannel channel = FileChannel.open(file.toPath(), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE); return new BinaryGeoGrid(channel, sizeX, sizeY, scale, origin, offsetX, offsetY, sourceCRS, fillGrid); } catch (final IOException e) { throw new GeoGridException("Could not find binary grid file: " + file.getAbsolutePath(), e); } }
From source file:com.gmt2001.datastore.IniStore.java
private void SaveFile(String fName, IniFile data) { if (data == null) { return;/*from w w w .ja va 2 s. c o m*/ } try { String wdata = ""; Object[] adata = data.data.keySet().toArray(); Object[] akdata; Object[] avdata; for (int i = 0; i < adata.length; i++) { if (i > 0) { wdata += "\r\n"; } if (!((String) adata[i]).equals("")) { wdata += "[" + ((String) adata[i]) + "]\r\n"; } akdata = data.data.get(((String) adata[i])).keySet().toArray(); avdata = data.data.get(((String) adata[i])).values().toArray(); for (int b = 0; b < akdata.length; b++) { wdata += ((String) akdata[b]) + "=" + ((String) avdata[b]) + "\r\n"; } } if (!Files.isDirectory(Paths.get("./" + inifolder + "/"))) { Files.createDirectory(Paths.get("./" + inifolder + "/")); } Files.write(Paths.get("./" + inifolder + "/" + fName + ".ini"), wdata.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); changed.remove(fName); } catch (IOException ex) { com.gmt2001.Console.err.printStackTrace(ex); } }
From source file:org.apache.nifi.minifi.FlowParser.java
/** * Writes a given XML Flow out to the specified path. * * @param flowDocument flowDocument of the associated XML content to write to disk * @param flowXmlPath path on disk to write the flow * @throws IOException if there are issues in accessing the target destination for the flow * @throws TransformerException if there are issues in the xml transformation process *//*from w w w .ja v a 2 s . c o m*/ public void writeFlow(final Document flowDocument, final Path flowXmlPath) throws IOException, TransformerException { final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final Source xmlSource = new DOMSource(flowDocument); final Result outputTarget = new StreamResult(outputStream); TransformerFactory.newInstance().newTransformer().transform(xmlSource, outputTarget); final InputStream is = new ByteArrayInputStream(outputStream.toByteArray()); try (final OutputStream output = Files.newOutputStream(flowXmlPath, StandardOpenOption.WRITE, StandardOpenOption.CREATE); final OutputStream gzipOut = new GZIPOutputStream(output);) { FileUtils.copy(is, gzipOut); } }
From source file:org.apache.bookkeeper.common.conf.ConfigDef.java
public void save(Path path) throws IOException { try (OutputStream stream = Files.newOutputStream(path, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING)) { save(stream);// w ww . ja va2 s . co m } }
From source file:com.github.jinahya.simple.file.back.LocalFileBackTest.java
@Test(enabled = true, invocationCount = 1) public void copy() throws IOException, FileBackException { fileContext.fileOperationSupplier(() -> FileOperation.COPY); final ByteBuffer sourceFileKey = randomFileKey(); fileContext.sourceKeySupplier(() -> sourceFileKey); final ByteBuffer targetFileKey = randomFileKey(); fileContext.targetKeySupplier(() -> targetFileKey); final Path sourceLeafPath = LocalFileBack.leafPath(rootPath, sourceFileKey, true); final byte[] fileBytes = randomFileBytes(); final boolean fileWritten = Files.isRegularFile(sourceLeafPath) || current().nextBoolean(); if (fileWritten) { Files.write(sourceLeafPath, fileBytes, StandardOpenOption.CREATE, StandardOpenOption.WRITE); logger.trace("file written"); }/*from w ww.j a va 2 s . c o m*/ fileBack.operate(fileContext); }
From source file:ubicrypt.core.Utils.java
public static Observable<Long> write(final Path fullPath, final InputStream inputStream) { return Observable.create(subscriber -> { try {//from w w w .ja v a 2 s . c o m final AtomicLong offset = new AtomicLong(0); final AsynchronousFileChannel afc = AsynchronousFileChannel.open(fullPath, StandardOpenOption.WRITE, StandardOpenOption.CREATE); afc.lock(new Object(), new CompletionHandler<FileLock, Object>() { @Override public void completed(final FileLock lock, final Object attachment) { //acquired lock final byte[] buf = new byte[1 << 16]; try { final int len = inputStream.read(buf); if (len == -1) { unsubscribe(subscriber, inputStream, lock); return; } afc.write(ByteBuffer.wrap(Arrays.copyOfRange(buf, 0, len)), offset.get(), null, new CompletionHandler<Integer, Object>() { @Override public void completed(final Integer result, final Object attachment) { //written chunk of bytes subscriber.onNext(offset.addAndGet(result)); final byte[] buf = new byte[1 << 16]; int len; try { len = inputStream.read(buf); if (len == -1) { unsubscribe(subscriber, inputStream, lock); log.debug("written:{}", fullPath); return; } } catch (final IOException e) { subscriber.onError(e); return; } if (len == -1) { unsubscribe(subscriber, inputStream, lock); log.debug("written:{}", fullPath); return; } afc.write(ByteBuffer.wrap(Arrays.copyOfRange(buf, 0, len)), offset.get(), null, this); } @Override public void failed(final Throwable exc, final Object attachment) { subscriber.onError(exc); } }); } catch (final Exception e) { close(inputStream, lock); subscriber.onError(e); } } @Override public void failed(final Throwable exc, final Object attachment) { log.error("error on getting lock for:{}, error:{}", fullPath, exc.getMessage()); try { inputStream.close(); } catch (final IOException e) { } subscriber.onError(exc); } }); } catch (final Exception e) { log.error("error on file:{}", fullPath); subscriber.onError(e); } }); }
From source file:com.evolveum.midpoint.provisioning.impl.manual.TestSemiManual.java
private void replaceInCsv(String[] data) throws IOException { List<String> lines = Files.readAllLines(Paths.get(CSV_TARGET_FILE.getPath())); 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)); }/* ww w . jav a 2 s. co m*/ } Files.write(Paths.get(CSV_TARGET_FILE.getPath()), lines, StandardOpenOption.WRITE); }
From source file:com.netflix.genie.web.services.impl.DiskJobFileServiceImpl.java
/** * {@inheritDoc}/* w w w .j a va 2 s . c o m*/ */ @Override // TODO: We should be careful about how large the byte[] is. Perhaps we should have precondition to protect memory // or we should wrap calls to this in something that chunks it off an input stream or just take this in as // input stream public void updateFile(final String jobId, final String relativePath, final long startByte, final byte[] data) throws IOException { log.debug("Attempting to write {} bytes from position {} into log file {} for job {}", data.length, startByte, relativePath, jobId); final Path jobFile = this.jobsDirRoot.resolve(jobId).resolve(relativePath); if (Files.notExists(jobFile)) { // Make sure all the directories exist on disk final Path logFileParent = jobFile.getParent(); if (logFileParent != null) { this.createOrCheckDirectory(logFileParent); } } else if (Files.isDirectory(jobFile)) { // TODO: Perhaps this should be different exception throw new IllegalArgumentException(relativePath + " is a directory not a file. Unable to update"); } try (FileChannel fileChannel = FileChannel.open(jobFile, EnumSet.of(StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.SPARSE))) { // Move the byteChannel to the start byte fileChannel.position(startByte); // The size and length are ignored in this implementation as we just assume we're writing everything atm // TODO: Would it be better to provide an input stream and buffer the output? final ByteBuffer byteBuffer = ByteBuffer.wrap(data); while (byteBuffer.hasRemaining()) { fileChannel.write(byteBuffer); } } }
From source file:at.ac.tuwien.infosys.util.ImageUtil.java
private void saveFile(URL url, Path file) throws IOException { ReadableByteChannel rbc = Channels.newChannel(url.openStream()); FileChannel channel = FileChannel.open(file, EnumSet.of(StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)); channel.transferFrom(rbc, 0, Long.MAX_VALUE); channel.close();//from w w w . j a v a 2 s.co m }
From source file:org.tinywind.springi18nconverter.converter.ExcelConverter.java
@Override @SuppressWarnings("unchecked") public void decode(File sourceFile, String targetDir, String targetEncoding, Boolean describeByNative) { final String sourceFileName = sourceFile.getName().toLowerCase(); if (Arrays.stream(JS_POSTFIX_ARRAY).filter( postfix -> sourceFileName.lastIndexOf(postfix) == sourceFileName.length() - postfix.length()) .count() == 0)// w w w .ja v a 2 s. co m return; try { final Map<String, List<String>> stringListMap = new HashMap<>(); final FileInputStream file = new FileInputStream(sourceFile); Iterator<Row> rowIterator; try { final XSSFWorkbook workbook = new XSSFWorkbook(file); final XSSFSheet sheet = workbook.getSheetAt(0); rowIterator = sheet.iterator(); } catch (OfficeXmlFileException e) { System.err.println(" exception:" + e.getMessage()); final HSSFWorkbook workbook = new HSSFWorkbook(file); final HSSFSheet sheet = workbook.getSheetAt(0); rowIterator = sheet.iterator(); } while (rowIterator.hasNext()) { final Row row = rowIterator.next(); final String key = row.getCell(COLUMN_KEY).getStringCellValue(); final String language = row.getCell(COLUMN_LANG).getStringCellValue(); final String value = row.getCell(COLUMN_VALUE).getStringCellValue().trim(); if (StringUtils.isEmpty(key) || StringUtils.isEmpty(language) || StringUtils.isEmpty(value)) continue; List<String> stringList = stringListMap.get(language); if (stringList == null) { stringList = new ArrayList<>(); stringListMap.put(language, stringList); } final String newLine = "\\\n"; String lastValue = "", token; final BufferedReader reader = new BufferedReader(new StringReader(value)); while ((token = reader.readLine()) != null) lastValue += token + newLine; reader.close(); if (lastValue.lastIndexOf(newLine) == lastValue.length() - newLine.length()) lastValue = lastValue.substring(0, lastValue.length() - newLine.length()); addProperty(stringList, key, lastValue, describeByNative); } for (String language : stringListMap.keySet()) { Files.write(Paths.get(new File(targetDir, messagesPropertiesFileName(language)).toURI()), stringListMap.get(language), Charset.forName(targetEncoding), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE); } } catch (Exception e) { System.err.println(" FAIL to convert: " + sourceFile.getAbsolutePath()); e.printStackTrace(); } }