Example usage for java.nio.file StandardOpenOption WRITE

List of usage examples for java.nio.file StandardOpenOption WRITE

Introduction

In this page you can find the example usage for java.nio.file StandardOpenOption WRITE.

Prototype

StandardOpenOption WRITE

To view the source code for java.nio.file StandardOpenOption WRITE.

Click Source Link

Document

Open for write access.

Usage

From source file:org.cryptomator.cryptofs.CryptoFileSystemProviderIntegrationTest.java

@Test
public void testOpenAndCloseFileChannel() throws IOException {
    FileSystem fs = CryptoFileSystemProvider.newFileSystem(tmpPath,
            cryptoFileSystemProperties().withPassphrase("asd").build());
    try (FileChannel ch = FileChannel.open(fs.getPath("/foo"),
            EnumSet.of(StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW))) {
        Assert.assertTrue(ch instanceof CryptoFileChannel);
    }/*ww  w . j av  a 2 s .  c o m*/
}

From source file:org.schedulesdirect.api.utils.HttpUtils.java

static public void captureToDisk(String msg) {
    Config conf = Config.get();//from  w  w w  .j a  va 2s.c o  m
    if (conf.captureHttpComm()) {
        if (!auditSetup)
            setupAudit();

        try {
            if (AUDIT_LOG != null)
                synchronized (HttpUtils.class) {
                    Files.write(AUDIT_LOG, msg.getBytes("UTF-8"), StandardOpenOption.APPEND,
                            StandardOpenOption.WRITE, StandardOpenOption.CREATE);
                }
        } catch (IOException e) {
            LOG.error("Unable to write capture file, logging at trace level instead!", e);
            LOG.trace(msg);
        }
    }
}

From source file:org.kalypso.kalypsosimulationmodel.core.wind.BinaryGeoGridWrapperForPairsModel.java

/**
 * Opens an existing grid.<br>/* w ww .j  a v a  2  s  .com*/
 * Dispose the grid after it is no more needed in order to release the given resource.
 *
 * @param writeable
 *          If <code>true</code>, the grid is opened for writing and a {@link IWriteableGeoGrid} is returned.
 */
public static BinaryGeoGridWrapperForPairsModel openGrid(final URL url, final Coordinate origin,
        final Coordinate offsetX, final Coordinate offsetY, final String sourceCRS, final boolean writeable)
        throws IOException {
    /* Tries to find a file from the given url. */
    File fileFromUrl = ResourceUtilities.findJavaFileFromURL(url);
    File binFile = null;
    if (fileFromUrl == null)
        fileFromUrl = FileUtils.toFile(url);

    if (fileFromUrl == null) {
        /*
         * If url cannot be converted to a file, write its contents to a temporary file which will be deleted after the
         * grid gets disposed.
         */
        fileFromUrl = File.createTempFile("local", ".bin"); //$NON-NLS-1$ //$NON-NLS-2$
        fileFromUrl.deleteOnExit();
        FileUtils.copyURLToFile(url, fileFromUrl);
        binFile = fileFromUrl; // set in order to delete on dispose
    }

    FileChannel channel;
    if (writeable)
        channel = FileChannel.open(fileFromUrl.toPath(), StandardOpenOption.WRITE, StandardOpenOption.READ);
    else
        channel = FileChannel.open(fileFromUrl.toPath(), StandardOpenOption.READ);

    return new BinaryGeoGridWrapperForPairsModel(channel, binFile, origin, offsetX, offsetY, sourceCRS);
}

From source file:org.diorite.impl.plugin.PluginManagerImpl.java

public static void saveCache() {
    try {//from   w ww  .  j  a v a2s .com
        Files.write(new File("pluginsCache.txt").toPath(),
                mainClassCache.entrySet().stream().map(e -> e.getValue() + CACHE_PATTERN_SEP + e.getKey())
                        .collect(Collectors.toList()),
                StandardCharsets.UTF_8, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
    } catch (final Exception e) {
        if (CoreMain.isEnabledDebug()) {
            e.printStackTrace();
        }
    }
}

From source file:cn.codepub.redis.directory.RedisLockFactory.java

@Override
public Lock obtainLock(@NonNull Directory dir, String lockName) throws IOException {
    if (!(dir instanceof RedisDirectory)) {
        throw new IllegalArgumentException("Expect argument of type [" + RedisDirectory.class.getName() + "]!");
    }//from  w  ww . j av  a 2  s. co m
    Path lockFile = lockFileDirectory.resolve(lockName);
    try {
        Files.createFile(lockFile);
        log.debug("Lock file path = {}", lockFile.toFile().getAbsolutePath());
    } catch (IOException ignore) {
        //ignore
        log.debug("Lock file already exists!");
    }
    final Path realPath = lockFile.toRealPath();
    final FileTime creationTime = Files.readAttributes(realPath, BasicFileAttributes.class).creationTime();
    if (LOCK_HELD.add(realPath.toString())) {
        FileChannel fileChannel = null;
        FileLock lock = null;
        try {
            fileChannel = FileChannel.open(realPath, StandardOpenOption.CREATE, StandardOpenOption.WRITE);
            lock = fileChannel.tryLock();
            if (lock != null) {
                return new RedisLock(lock, fileChannel, realPath, creationTime);
            } else {
                throw new LockObtainFailedException("Lock held by another program: " + realPath);
            }
        } finally {
            if (lock == null) {
                IOUtils.closeQuietly(fileChannel);
                clearLockHeld(realPath);
            }
        }
    } else {
        throw new LockObtainFailedException("Lock held by this virtual machine: " + realPath);
    }
}

From source file:org.eclipse.packagedrone.utils.rpm.build.PayloadRecorder.java

public PayloadRecorder(final boolean autoFinish) throws IOException {
    this.autoFinish = autoFinish;

    this.tempFile = Files.createTempFile("rpm-", null);

    try {/*w  ww . j a v a2s.  co m*/
        this.fileStream = new BufferedOutputStream(Files.newOutputStream(this.tempFile,
                StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING));

        this.payloadCounter = new CountingOutputStream(this.fileStream);

        final GZIPOutputStream payloadStream = new GZIPOutputStream(this.payloadCounter);
        this.archiveCounter = new CountingOutputStream(payloadStream);

        // setup archive stream

        this.archiveStream = new CpioArchiveOutputStream(this.archiveCounter, CpioConstants.FORMAT_NEW, 4,
                "UTF-8");
    } catch (final IOException e) {
        Files.deleteIfExists(this.tempFile);
        throw e;
    }
}

From source file:org.basinmc.maven.plugins.minecraft.launcher.DownloadDescriptor.java

/**
 * Fetches the artifact from the server and stores it in a specified file.
 *//*from  ww w .  j  av a 2  s .  co m*/
public void fetch(@Nonnull Path outputFile) throws IOException {
    HttpClient client = HttpClients.createMinimal();

    try {
        HttpGet request = new HttpGet(this.url.toURI());
        HttpResponse response = client.execute(request);

        StatusLine line = response.getStatusLine();

        if (line.getStatusCode() != 200) {
            throw new IOException(
                    "Unexpected status code: " + line.getStatusCode() + " - " + line.getReasonPhrase());
        }

        try (InputStream inputStream = response.getEntity().getContent()) {
            try (FileChannel fileChannel = FileChannel.open(outputFile, StandardOpenOption.CREATE,
                    StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) {
                try (ReadableByteChannel inputChannel = Channels.newChannel(inputStream)) {
                    fileChannel.transferFrom(inputChannel, 0, Long.MAX_VALUE);
                }
            }
        }
    } catch (URISyntaxException ex) {
        throw new IOException("Received invalid URI from API: " + ex.getMessage(), ex);
    }
}

From source file:org.jhk.pulsing.web.aspect.UserDaoAspect.java

@AfterReturning(pointcut = "execution(org.jhk.pulsing.web.common.Result+ org.jhk.pulsing.web.dao.*.UserDao.*(..))", returning = "result")
public void patchUser(JoinPoint joinPoint, Result<User> result) {
    if (result.getCode() != SUCCESS) {
        return;/*w ww. jav a2s . c  om*/
    }

    User user = result.getData();
    user.setPassword(""); //blank out password
    Picture picture = user.getPicture();

    _LOGGER.debug("UserDaoAspect.setPictureUrl" + user);

    if (picture != null && picture.getName() != null) {

        ByteBuffer pBuffer = picture.getContent();
        String path = applicationContext.getServletContext().getRealPath("/resources/img");
        File parent = Paths.get(path).toFile();
        if (!parent.exists()) {
            parent.mkdirs();
        }

        String pFileName = user.getId().getId() + "_" + pBuffer.hashCode() + "_" + picture.getName();
        File pFile = Paths.get(path, pFileName).toFile();

        if (!pFile.exists()) {
            try (OutputStream fStream = Files.newOutputStream(pFile.toPath(), StandardOpenOption.CREATE_NEW,
                    StandardOpenOption.WRITE)) {
                fStream.write(pBuffer.array());
            } catch (IOException iException) {
                iException.printStackTrace();
                pFile = null;
            }
        }

        if (pFile != null) {
            _LOGGER.debug("UserDaoAspect Setting picture url - " + _RESOURCE_PREFIX + pFile.getName());
            picture.setUrl(_RESOURCE_PREFIX + pFile.getName());
        }
    }

}

From source file:divconq.util.IOUtil.java

public static OperationResult saveEntireFile(Path dest, String content) {
    OperationResult or = new OperationResult();

    try {//from   w  w w. j  a v  a2 s.com
        Files.createDirectories(dest.getParent());
        Files.write(dest, Utf8Encoder.encode(content), StandardOpenOption.CREATE,
                StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE, StandardOpenOption.SYNC);
    } catch (Exception x) {
        or.error(1, "Error saving file contents: " + x);
    }

    return or;
}