Java 类java.nio.file.StandardOpenOption 实例源码

项目:MpiTaskFramework    文件:SharedSystemData.java   
/**
 * Constructor.
 * @throws IOException 
 */
public SharedSystemData(String path, boolean create) throws IOException {
    File f = new File(path);

    if (create) {
        if (f.exists()) {
            System.out.println("Existing system detected, deleting");
            f.delete(); // Delete if present.
        }
    } else {
        if (!f.exists()) {
            System.err.println("ERROR, system dont exist");
            System.exit(-1);
        }
    }
    channel = FileChannel.open(f.toPath(), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
    buffer = channel.map(MapMode.READ_WRITE, 0, 4000);

    if (create) {
        setNextTaskId(0);
        setShutdownSignal(false);
    }
}
项目:Re-Collector    文件:ChunkReaderScheduler.java   
public void followFile(Path file, FileInput.InitialReadPosition customInitialReadPosition) throws IOException {
    synchronized (this) {
        if (isFollowingFile(file)) {
            log.debug("Not following file {} because it's already followed.", file);
            return;
        }

        log.debug("Following file {}", file);

        final AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(file, StandardOpenOption.READ);
        final ChunkReader chunkReader = new ChunkReader(input, file, fileChannel, chunkQueue, readerBufferSize, customInitialReadPosition, this);
        final ScheduledFuture<?> chunkReaderFuture = scheduler.scheduleAtFixedRate(chunkReader, 0, readerInterval, TimeUnit.MILLISECONDS);

        chunkReaderTasks.putIfAbsent(file, new ChunkReaderTask(chunkReaderFuture, fileChannel));
    }
}
项目:Elasticsearch    文件:LocalTranslog.java   
private FileChannel openReader(long generationId) throws IOException {
    ensureOpen();
    if (readChannels.containsKey(generationId)) {
        return readChannels.get(generationId);
    }
    try {
        Path translogFilePath = this.translogPath.resolve(getFileNameFromId(tmpTranslogGeneration.get()));
        if (!Files.exists(translogFilePath)) {
            return null;
        }
        // maybe a lot of readers try to open reader and put it to readChannel cache, because read lock is shared
        FileChannel readChannel = FileChannel.open(translogFilePath, StandardOpenOption.READ);
        FileChannel originReadChannel = readChannels.putIfAbsent(generationId, readChannel);
        if (originReadChannel != null) {
            IOUtils.close(readChannel);
            return originReadChannel;
        } else {
            return readChannel;
        }
    } catch (Throwable e) {
        throw e;
    }
}
项目:buckaroo    文件:DownloadTask.java   
public static Observable<DownloadProgress> download(final URI url, final Path target, final boolean overwrite) {

        Preconditions.checkNotNull(url);
        Preconditions.checkNotNull(target);

        return Single.fromCallable(() -> {

            final Path parent = target.getParent();

            if (parent != null && !Files.exists(parent)) {
                Files.createDirectories(parent);
            }

            if (overwrite) {
                return Files.newOutputStream(target, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
            }

            return Files.newOutputStream(target, StandardOpenOption.CREATE_NEW);
        }).flatMapObservable(outputStream -> download(url, outputStream));
    }
项目:smart-testing    文件:NewTestsGitBasedDetectorTest.java   
@Test
public void should_find_local_newly_staged_files_as_new() throws IOException, GitAPIException {
    //given
    Configuration configuration = createConfiguration("a4261d5", "1ee4abf");
    final File testFile = gitFolder.newFile("core/src/test/java/org/arquillian/smart/testing/CalculatorTest.java");
    Files.write(testFile.toPath(), getContentsOfClass().getBytes(), StandardOpenOption.APPEND);

    GitRepositoryOperations.addFile(gitFolder.getRoot(), testFile.getAbsolutePath());

    final NewTestsDetector newTestsDetector =
        new NewTestsDetector(new GitChangeResolver(), new NoopStorage(), gitFolder.getRoot(), path -> true, configuration);

    // when
    final Collection<TestSelection> newTests = newTestsDetector.getTests();

    // then
    assertThat(newTests).extracting(TestSelection::getClassName)
        .containsOnly("org.arquillian.smart.testing.CalculatorTest",
            "org.arquillian.smart.testing.vcs.git.NewFilesDetectorTest");
}
项目:r8    文件:JumboString.java   
public static void generate() throws IOException {
  int stringsPerFile = (1 << 14);
  for (int fileNumber = 0; fileNumber < 2; fileNumber++) {
    Path path = FileSystems.getDefault().getPath("StringPool" + fileNumber + ".java");
    PrintStream out = new PrintStream(
        Files.newOutputStream(path, StandardOpenOption.CREATE, StandardOpenOption.APPEND));

    out.println(
        "// Copyright (c) 2016, the R8 project authors. Please see the AUTHORS file");
    out.println(
        "// for details. All rights reserved. Use of this source code is governed by a");
    out.println("// BSD-style license that can be found in the LICENSE file.");
    out.println("package jumbostring;");
    out.println();
    out.println("class StringPool" + fileNumber + " {");

    int offset = fileNumber * stringsPerFile;
    for (int i = offset; i < offset + stringsPerFile; i++) {
      out.println("  public static final String s" + i + " = \"" + i + "\";");
    }
    out.println("}");
    out.close();
  }
}
项目:fuse-nio-adapter    文件:OpenOptionsUtil.java   
public Set<OpenOption> fuseOpenFlagsToNioOpenOptions(Set<OpenFlags> flags) {
    Set<OpenOption> result = new HashSet<>();
    if (flags.contains(OpenFlags.O_RDONLY) || flags.contains(OpenFlags.O_RDWR)) {
        result.add(StandardOpenOption.READ);
    }
    if (flags.contains(OpenFlags.O_WRONLY) || flags.contains(OpenFlags.O_RDWR)) {
        result.add(StandardOpenOption.WRITE);
    }
    if (flags.contains(OpenFlags.O_APPEND)) {
        result.add(StandardOpenOption.APPEND);
    }
    if (flags.contains(OpenFlags.O_TRUNC)) {
        result.add(StandardOpenOption.TRUNCATE_EXISTING);
    }
    return result;
}
项目:kafka-0.11.0.0-src-with-comment    文件:StateDirectoryTest.java   
@Test
public void shouldReleaseTaskStateDirectoryLock() throws Exception {
    final TaskId taskId = new TaskId(0, 0);
    final File taskDirectory = directory.directoryForTask(taskId);

    directory.lock(taskId, 1);
    directory.unlock(taskId);

    try (
        final FileChannel channel = FileChannel.open(
            new File(taskDirectory, StateDirectory.LOCK_FILE_NAME).toPath(),
            StandardOpenOption.CREATE,
            StandardOpenOption.WRITE)
    ) {
        channel.tryLock();
    }
}
项目:drinkwater-java    文件:PropertiesTest.java   
@Test
public void shouldWorkWithApplicationPropertiesFormOtherLocation() throws Exception {

    //create an external propertiesfile
    File propertiesFile = folder.newFile("external.properties");

    Files.write(Paths.get(propertiesFile.getPath()),
            "info=info from external properties file".getBytes(),
            StandardOpenOption.APPEND);

    DrinkWaterApplication propertiesApp = DrinkWaterApplication.create("PropertiesTest-application");
    propertiesApp.addServiceBuilder(new PropertiesTestConfiguration("test-external-properties", propertiesFile.getPath()));

    try {
        propertiesApp.start();

        String result = httpGetString(String.format("http://127.0.0.1:%s/test-external-properties/info",
                propertiesApp.getServiceProperty("test-external-properties", RestService.REST_PORT_KEY))).result();
        assertEquals("info from external properties file", result);

    }
    finally {
        propertiesApp.stop();
    }
}
项目:LotusCloud    文件:Database.java   
private void initialize() {
    try {
        if (!dbFile.exists()) {
            Files.write(dbFile.toPath(), "".getBytes(), StandardOpenOption.CREATE);
        }
        String dbContent = new String(Files.readAllBytes(dbFile.toPath()), StandardCharsets.UTF_8);
        for (String line : dbContent.split("/-/")) {
            if (line.trim().equals("")) {
                continue;
            }
            String[] keyValue = line.split("=");
            values.put(keyValue[0], new String(Base64.getDecoder().decode(keyValue[1]), StandardCharsets.UTF_8));
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}
项目:mux2fs    文件:MirrorFsTest.java   
@Test
public void testReleaseClosesOpenFileChannel()
        throws Exception {
    // Given
    FileHandleFiller filler = mock(FileHandleFiller.class);
    ArgumentCaptor<Integer> handleCaptor = ArgumentCaptor.forClass(Integer.class);
    doNothing().when(filler).setFileHandle(handleCaptor.capture());
    Path fooBar = mockPath(mirrorRoot, "foo.bar");
    FileChannel fileChannel = mock(FileChannel.class);
    when(fileSystem.provider().newFileChannel(eq(fooBar), eq(set(StandardOpenOption.READ)))).thenReturn(fileChannel);
    fs.open("foo.bar", filler);
    // When
    int result = fs.release("foo.bar", handleCaptor.getValue());
    // Then
    assertThat(result).isEqualTo(SUCCESS);
    verify(fileChannelCloser).close(fileChannel);
    verifyNoMoreInteractions(fileChannel);
}
项目:jenkins-client-plugin    文件:BaseStep.java   
public static boolean withTempInput(String prefix, String content,
        WithTempInputRunnable runnable) throws IOException,
        InterruptedException {
    Path tmp = null;
    try {
        if (content != null) {
            tmp = Files.createTempFile(prefix, ".tmp");
            ArrayList<String> list = new ArrayList<String>(1);
            list.add(content);
            Files.write(tmp, list, StandardCharsets.UTF_8,
                    StandardOpenOption.WRITE);
        }
        return runnable.perform((tmp == null) ? null : tmp.toAbsolutePath()
                .toString());
    } finally {
        if (tmp != null) {
            Files.delete(tmp);
        }
    }
}
项目:alfresco-repository    文件:BulkImportTest.java   
private void unpack(Path source, Path destFile)
{
    Path archive = source.resolve("testbulk.gz");

    try (GZIPInputStream gzis = new GZIPInputStream(Files.newInputStream(archive));
         OutputStream out = Files.newOutputStream(destFile, StandardOpenOption.CREATE))
    {
        byte[] buffer = new byte[1024];
        int len;
        while ((len = gzis.read(buffer)) > 0) 
        {
            out.write(buffer, 0, len);
        }
    }
    catch (IOException ex)
    {
        ex.printStackTrace();   
    }
}
项目:jpeek    文件:DefaultBaseTest.java   
@Test
public void listsFiles() throws IOException {
    final Path temp = Files.createTempDirectory("");
    temp.resolve("a/b/c").toFile().mkdirs();
    Files.write(
        temp.resolve("a/b/c/x.java"), "Hello".getBytes(),
        StandardOpenOption.CREATE_NEW
    );
    Files.write(
        temp.resolve("a/z.class"), "".getBytes(),
        StandardOpenOption.CREATE_NEW
    );
    MatcherAssert.assertThat(
        new DefaultBase(temp).files(),
        Matchers.iterableWithSize(Matchers.greaterThan(2))
    );
}
项目:centraldogma    文件:CommitIdDatabaseTest.java   
@Test
public void truncatedDatabase() throws Exception {
    db.put(Revision.INIT, randomCommitId());
    db.close();

    // Truncate the database file.
    try (FileChannel f = FileChannel.open(new File(tmpDir.getRoot(), "commit_ids.dat").toPath(),
                     StandardOpenOption.APPEND)) {

        assertThat(f.size()).isEqualTo(24);
        f.truncate(23);
    }

    assertThatThrownBy(() -> new CommitIdDatabase(tmpDir.getRoot()))
            .isInstanceOf(StorageException.class)
            .hasMessageContaining("incorrect file length");
}
项目:smart-testing    文件:NewTestsGitBasedDetectorTest.java   
@Test
public void should_not_find_local_modified_file_as_new_when_using_commit_range() throws IOException {
    //given
    Configuration configuration = createConfiguration("a4261d5", "1ee4abf");
    final Path testFile = Paths.get(gitFolder.getRoot().getAbsolutePath(),
        "core/src/test/java/org/arquillian/smart/testing/FilesTest.java");

    Files.write(testFile, "//This is a test".getBytes(), StandardOpenOption.APPEND);

    final NewTestsDetector newTestsDetector =
        new NewTestsDetector(new GitChangeResolver(), new NoopStorage(), gitFolder.getRoot(), path -> true, configuration);

    // when
    final Collection<TestSelection> newTests = newTestsDetector.getTests();

    // then
    assertThat(newTests).extracting(TestSelection::getClassName)
        .doesNotContain("org.arquillian.smart.testing.FilesTest");
}
项目:CPUEmulator    文件:Compiler.java   
@Deprecated
public static void main(String [] args) throws IOException
{
    // Lets the user choose his outputing file
    String filename = "testing.out";
    // Initializes the path to said file
    Path path_to_program = Paths.get(filename);
    // Clears the file by writing nothing
    Files.write(path_to_program, new byte[]{});
    // Actual program in op-codes
    byte[][] instructions = {{CPUMain.PUSH, 0x45}, {CPUMain.POP, 0x00}, {CPUMain.PLACE, 0x03, 0x35}, {CPUMain.DIV, 0x02, 0x03}, {CPUMain.PRINT, 0x02}};
    for (byte[] instruction: instructions)
    {
        // Write to file the desired bytes
        Files.write(path_to_program, instruction, StandardOpenOption.APPEND);
    }
    // Output completion of the process to the user
    System.out.println("Done writing program to " + filename);
}
项目:openjdk-jdk10    文件:CheckZombieLockTest.java   
/**
 * Setup all the files and directories needed for the tests
 *
 * @return writable directory created that needs to be deleted when done
 * @throws RuntimeException
 */
private static File setup() throws RuntimeException {
    // First do some setup in the temporary directory (using same logic as
    // FileHandler for %t pattern)
    String tmpDir = System.getProperty("java.io.tmpdir"); // i.e. %t
    if (tmpDir == null) {
        tmpDir = System.getProperty("user.home");
    }
    File tmpOrHomeDir = new File(tmpDir);
    // Create a writable directory here (%t/writable-lockfile-dir)
    File writableDir = new File(tmpOrHomeDir, WRITABLE_DIR);
    if (!createFile(writableDir, true)) {
        throw new RuntimeException("Test setup failed: unable to create"
                + " writable working directory "
                + writableDir.getAbsolutePath() );
    }

    // try to determine whether file locking is supported
    final String uniqueFileName = UUID.randomUUID().toString()+".lck";
    try {
        FileChannel fc = FileChannel.open(Paths.get(writableDir.getAbsolutePath(),
                uniqueFileName),
                StandardOpenOption.CREATE_NEW, StandardOpenOption.APPEND,
                StandardOpenOption.DELETE_ON_CLOSE);
        try {
            fc.tryLock();
        } catch(IOException x) {
            supportsLocking = false;
        } finally {
            fc.close();
        }
    } catch (IOException t) {
        // should not happen
        System.err.println("Failed to create new file " + uniqueFileName +
                " in " + writableDir.getAbsolutePath());
        throw new RuntimeException("Test setup failed: unable to run test", t);
    }
    return writableDir;
}
项目:tqdev-metrics    文件:PrometheusLogReporterTest.java   
/**
 * Should remove files.
 *
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
@Test
public void shouldRemoveFiles() throws IOException {
    registry.add("jdbc.Statement.Duration", "select", 123);
    String line = "jdbc{host=\"localhost\",instance=\"Statement\",type=\"Duration\",type_instance=\"select\"} 123 1510373758000\n";
    Files.createFile(tempPath.resolve("1510373738123.prom"));
    Files.createFile(tempPath.resolve("1510373748123.prom"));
    Files.write(tempPath.resolve("1510373758123.prom"), line.getBytes(), StandardOpenOption.CREATE_NEW);
    boolean success = reporter.report();
    File[] promFiles = tempPath.toFile().listFiles((f, s) -> s.endsWith(".prom"));
    assertThat(success).isTrue();
    assertThat(promFiles.length).isEqualTo(2);
    assertThat(promFiles[0].getName()).isEqualTo("1510373748123.prom");
    assertThat(promFiles[1].getName()).isEqualTo("1510373758123.prom");
}
项目:openjdk-jdk10    文件:ClassAndLibraryNotMatchTest.java   
private void writeHelloWorld(String message) {
    String src = HELLO_WORLD_PRE + message + HELLO_WORLD_POST;
    try{
        Files.write(Paths.get(HELLO_WORLD_FILE), src.getBytes(), StandardOpenOption.CREATE);
    } catch (IOException e) {
        throw new Error("Can't write HelloWorld " + e, e);
    }
}
项目:mux2fs    文件:MuxFsTest.java   
@Test
public void testReadFromFailedMuxedFile()
        throws Exception {
    // Given
    FileHandleFiller filler = mock(FileHandleFiller.class);
    ArgumentCaptor<Integer> handleCaptor = ArgumentCaptor.forClass(Integer.class);
    doNothing().when(filler).setFileHandle(handleCaptor.capture());
    Path mkv = mockPath("file1.mkv");
    Path srt = mockPath("file1.eng.srt", 2893756L);
    mockShuffledDirectoryStream(mirrorRoot, mkv, srt);
    mockAttributes(mkv, 1);
    Muxer muxer = mock(Muxer.class);
    when(muxerFactory.from(mkv, srt, tempDir)).thenReturn(muxer);
    Path muxedFile = mockPath(tempDir, "file1-muxed.mkv");
    when(muxer.getOutput()).thenReturn(Optional.of(muxedFile));
    FileChannel fileChannel = mock(FileChannel.class);
    when(fileSystem.provider().newFileChannel(eq(muxedFile), eq(set(StandardOpenOption.READ)))).thenReturn(fileChannel);
    fs.open("file1.mkv", filler);
    Integer fileHandle = handleCaptor.getValue();
    when(muxer.state()).thenReturn(State.FAILED);
    // When
    int result = fs.read("file1.mkv", (data) -> fail(), 128, 64, fileHandle);
    // Then
    assertThat(result).isEqualTo(-ErrorCodes.EIO());
    verify(muxerFactory).from(mkv, srt, tempDir);
    verifyNoMoreInteractions(muxerFactory);
    verify(muxer).start();
    verify(muxer).waitForOutput();
    verify(muxer).getOutput();
    verify(muxer).state();
    verifyNoMoreInteractions(muxer);
    verify(filler).setFileHandle(gt(1));
    verifyNoMoreInteractions(fileChannel);
}
项目:personium-core    文件:SnapshotFile.java   
/**
 * Write to data pjson.
 * @param data Data to write
 */
public void writeDataPJson(String data) {
    Path pathInZip = pathMap.get(DATA_PJSON);
    try (BufferedWriter writer = Files.newBufferedWriter(pathInZip, Charsets.UTF_8,
            StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.APPEND)) {
        writer.write(data);
    } catch (IOException e) {
        throw PersoniumCoreException.Common.FILE_IO_ERROR.params("add data pjson to snapshot file").reason(e);
    }
}
项目:incubator-netbeans    文件:Stamps.java   
private ByteBuffer asByteBuffer(String cache, boolean direct, boolean mmap) {
    int[] len = new int[1];
    File cacheFile = file(cache, len);
    if (cacheFile == null) {
        return null;
    }

    try (FileChannel fc = FileChannel.open(cacheFile.toPath(), StandardOpenOption.READ)){
        ByteBuffer master;
        if (mmap) {
            master = fc.map(FileChannel.MapMode.READ_ONLY, 0, len[0]);
            master.order(ByteOrder.LITTLE_ENDIAN);
        } else {
            master = direct ? ByteBuffer.allocateDirect(len[0]) : ByteBuffer.allocate(len[0]);
            int red = fc.read(master);
            if (red != len[0]) {
                LOG.warning("Read less than expected: " + red + " expected: " + len + " for " + cacheFile); // NOI18N
                return null;
            }
            master.flip();
        }

        return master;
    } catch (IOException | InvalidPathException ex) {
        LOG.log(Level.WARNING, "Cannot read cache " + cacheFile, ex); // NOI18N
        return null;
    }
}
项目:StreamDeckCore    文件:IconHelper.java   
public static void createIconPackage(String pathToArchive, String pathToIcon, String[] pathToFrames,
        AnimationStack stack) throws URISyntaxException, IOException {
    Path path = Paths.get(pathToArchive);
    URI uri = new URI("jar", path.toUri().toString(), null);

    Map<String, String> env = new HashMap<>();
    env.put("create", "true");
    try (FileSystem fileSystem = FileSystems.newFileSystem(uri, env)) {
        Path iconPath = fileSystem.getPath("icon.png");
        // save main icon
        Files.copy(Paths.get(pathToIcon), iconPath, StandardCopyOption.REPLACE_EXISTING);
        // save animation, if exists
        Path animationFile = fileSystem.getPath("animation.json");
        if (stack != null) {
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            String text = gson.toJson(stack);
            Files.write(animationFile, text.getBytes("UTF-8"), StandardOpenOption.TRUNCATE_EXISTING,
                    StandardOpenOption.WRITE);
            // save animation frames
            if (pathToFrames != null) {
                for (int i = 0; i < pathToFrames.length; i++) {
                    if (pathToFrames[i] != null) {
                        Path iconSourcePath = Paths.get(pathToFrames[i]);
                        Path iconTargetPath = fileSystem.getPath(i + ".png");
                        Files.copy(iconSourcePath, iconTargetPath, StandardCopyOption.REPLACE_EXISTING);
                    }
                }
            }
        }
        fileSystem.close();
    }
}
项目:eadlsync    文件:EADLSyncCommand.java   
void updateCommitId(String commitId) throws IOException{
    if (YStatementConstants.COMMIT_ID_PATTERN.matcher(commitId).matches()) {
        try {
            Files.write(EADL_REVISION, commitId.getBytes(), StandardOpenOption.CREATE);
            CLI.println(String.format("\tsync id -> %s", commitId));
        } catch (IOException e) {
            LOG.error("Error writing new commit revision to file.", e);
            throw e;
        }
    } else {
        CLI.println(String.format("Commit was rejected by the se-repo\n\t%s", commitId));
    }
}
项目:openjdk-jdk10    文件:IgnoreSourceErrors.java   
void emitSample(Path file) throws IOException {
    String[] contents = {
        "/** A java file with errors */",
        "public static class Foo {}"
    };
    Files.write(file, Arrays.asList(contents), StandardOpenOption.CREATE);
}
项目:Elasticsearch    文件:TranslogWriter.java   
protected synchronized void checkpoint(long lastSyncPosition, int operationCounter, ChannelReference channelReference) throws IOException {
    try {
        channelReference.getChannel().force(false);
        writeCheckpoint(lastSyncPosition, operationCounter, channelReference.getPath().getParent(), channelReference.getGeneration(), StandardOpenOption.WRITE);
    } catch (Throwable ex) {
        closeWithTragicEvent(ex);
        throw ex;
    }
}
项目:aidos-node    文件:StorageScratchpad.java   
@Override
public void init() throws IOException {
    scratchpadChannel = FileChannel.open(Paths.get(SCRATCHPAD_FILE_NAME), StandardOpenOption.CREATE, StandardOpenOption.READ, StandardOpenOption.WRITE);
    transactionsToRequest = scratchpadChannel.map(FileChannel.MapMode.READ_WRITE, TRANSACTIONS_TO_REQUEST_OFFSET, TRANSACTIONS_TO_REQUEST_SIZE);
    analyzedTransactionsFlags = scratchpadChannel.map(FileChannel.MapMode.READ_WRITE, ANALYZED_TRANSACTIONS_FLAGS_OFFSET, ANALYZED_TRANSACTIONS_FLAGS_SIZE);
    analyzedTransactionsFlagsCopy = scratchpadChannel.map(FileChannel.MapMode.READ_WRITE, ANALYZED_TRANSACTIONS_FLAGS_COPY_OFFSET, ANALYZED_TRANSACTIONS_FLAGS_COPY_SIZE);  
}
项目:mux2fs    文件:MirrorFsTest.java   
@Test
public void testRelease()
        throws Exception {
    // Given
    FileHandleFiller filler = mock(FileHandleFiller.class);
    ArgumentCaptor<Integer> handleCaptor = ArgumentCaptor.forClass(Integer.class);
    doNothing().when(filler).setFileHandle(handleCaptor.capture());
    Path fooBar = mockPath(mirrorRoot, "foo.bar");
    when(fileSystem.provider().newFileChannel(eq(fooBar), eq(set(StandardOpenOption.READ)))).thenReturn(mock(FileChannel.class));
    fs.open("foo.bar", filler);
    // When
    int result = fs.release("foo.bar", handleCaptor.getValue());
    // Then
    assertThat(result).isEqualTo(SUCCESS);
}
项目:fuse-nio-adapter    文件:ReadWriteFileHandler.java   
public int truncate(Path path, long size) {
    try (FileChannel fc = FileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING)) {
        return 0;
    } catch (IOException e) {
        LOG.error("Truncating file feild.", e);
        return -ErrorCodes.EIO();
    }
}
项目:jdk8u-jdk    文件:KeytoolReaderP12Test.java   
/**
 * Decodes the base64 encoded keystore and writes into new file
 * @param name base64 encoded keystore name
 */
private static void convertToPFX(String name) throws IOException{
    File base64File = new File(SOURCE_DIRECTORY, name);
    File pkcs12File = new File(WORKING_DIRECTORY, name);
    byte[] input = Files.readAllBytes(base64File.toPath());
    Files.write(pkcs12File.toPath(), Base64.getMimeDecoder().
            decode(input), StandardOpenOption.CREATE);
}
项目:maven-git-code-format    文件:DefaulExecutable.java   
@Override
public Executable truncateWithTemplate(Supplier<InputStream> template, Object... values)
    throws IOException {
  try (InputStream inputStream = template.get()) {
    String rawContent = IOUtils.toString(inputStream);
    Object[] refinedValues = Stream.of(values).map(this::unixifyPath).toArray();
    String content = String.format(rawContent, refinedValues);
    Files.write(file, content.getBytes(), StandardOpenOption.TRUNCATE_EXISTING);
  }
  return this;
}
项目:reactive-jax-rs    文件:CustomerRepository.java   
public Publisher<Integer> save(Publisher<Customer> customers) throws IOException {
  AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE);
  AtomicLong offset = new AtomicLong(0);
  AtomicInteger resultCount = new AtomicInteger(0);
  SingleItemPublisher<Integer> resultPublisher = new SingleItemPublisher<>();
  Semaphore writeSemaphore = new Semaphore(1);
  writeSemaphore.acquireUninterruptibly();
  fileChannel.write(ByteBuffer.wrap("[".getBytes()), 0, resultPublisher,
      andThen((count, s) -> {
        writeSemaphore.release();
        customers.subscribe(pullEach((Customer customer, Subscription subscription) -> {
            String json = String.format("%s{\"firstName\": \"%s\", \"lastName\": \"%s\"}", offset.longValue() == 0 ? "" : ",",
                customer.getFirstName(), customer.getLastName());
            offset.addAndGet(count);
            writeSemaphore.acquireUninterruptibly();
            fileChannel.write(ByteBuffer.wrap(json.getBytes()), offset.get(), resultPublisher,
                andThen((size, c) -> {
                  writeSemaphore.release();
                  offset.addAndGet(size);
                  resultCount.incrementAndGet();
                  subscription.request(1);
                }));
          }).andThen(() -> {
            writeSemaphore.acquireUninterruptibly();
              fileChannel.write(ByteBuffer.wrap("]".getBytes()), offset.longValue(), resultPublisher,
                  andThen((d, e) -> {
                    writeSemaphore.release();
                    try {
                      fileChannel.close();
                      resultPublisher.publish(resultCount.intValue());
                    } catch (IOException error) {
                      resultPublisher.publish(error);
                    }
                  }));
          }).exceptionally(error -> resultPublisher.publish(error)));
      }));
  return resultPublisher;
}
项目:openjdk-jdk10    文件:ListOptionTest.java   
public static void main(String[] args) {
    try {
        Files.write(COMPILE_COMMAND_FILE, Arrays.asList(COMPILE_COMMAND),
                StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW);
    } catch (IOException e) {
        throw new Error("TESTBUG: can't write list file " + e, e);
    }
    OutputAnalyzer oa = JaotcTestHelper.compileLibrary("--compile-commands", COMPILE_COMMAND_FILE.toString(),
            "--class-name", JaotcTestHelper.getClassAotCompilationName(HelloWorldOne.class));
    oa.shouldHaveExitValue(0);
    File compiledLibrary = new File(JaotcTestHelper.DEFAULT_LIB_PATH);
    Asserts.assertTrue(compiledLibrary.exists(), "Compiled library file missing");
    Asserts.assertGT(compiledLibrary.length(), 0L, "Unexpected compiled library size");
    JaotcTestHelper.checkLibraryUsage(TESTED_CLASS_NAME, EXPECTED, UNEXPECTED);
}
项目:tqdev-metrics    文件:InfluxDbFileReporterTest.java   
/**
 * Should compress file.
 *
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
@Test
public void shouldCompressFile() throws IOException {
    registry.add("jdbc.Statement.Duration", "select", 123);
    String line = "jdbc,host=localhost,instance=Statement,type=Duration,type_instance=select value=123i 1510373758000000000\n";
    Files.write(tempPath.resolve("20171110.txt"), line.getBytes(), StandardOpenOption.CREATE_NEW);
    boolean success = reporter.report();
    File[] gzipFiles = tempPath.toFile().listFiles((f, s) -> s.endsWith(".gz"));
    File[] textFiles = tempPath.toFile().listFiles((f, s) -> s.endsWith(".txt"));
    assertThat(success).isTrue();
    assertThat(gzipFiles.length).isEqualTo(1);
    assertThat(gzipFiles[0].getName()).isEqualTo("20171110.txt.gz");
    assertThat(textFiles.length).isEqualTo(1);
    assertThat(textFiles[0].getName()).isEqualTo("20171111.txt");
}
项目:Meucci    文件:ModLoader.java   
private void writeTemplates(Modulo mod)throws IOException{
    if(mod.Tca.length==0 && mod.Ttype.length==0)
        return;
    Path p=Paths.get(cpath+"/"+mod.nome+".tin");
    try(ObjectOutputStream out=new ObjectOutputStream(new 
        BufferedOutputStream(Files.newOutputStream(p, StandardOpenOption.WRITE, 
            StandardOpenOption.CREATE)))){
        out.writeObject(mod.Ttype);
        out.writeObject(mod.Tca);
    }
}
项目:Pet-Supply-Store    文件:CreatorRunner.java   
@Override
public void run() {
    long imgID = ImageIDFactory.ID.getNextImageID();
    Random rand = new Random(productID);

    // All products must be added to the database
    imgDB.setImageMapping(productID, imgID, size);

    // Resolve path and create a new image
    Path imgFile = workingDir.resolve(String.valueOf(imgID));

    BufferedImage img = ImageCreator.createImage(shapesPerImage, categoryImage, size, rand);
    ByteArrayOutputStream stream = new ByteArrayOutputStream();

    try {
        ImageIO.write(img, StoreImage.STORE_IMAGE_FORMAT, stream);
        Files.write(imgFile, Base64.getEncoder().encode(stream.toByteArray()), 
                StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);
    } catch (IOException ioException) {
        if (!(ioException instanceof ClosedByInterruptException)) {
            log.warn("An IOException occured while writing image with ID " + String.valueOf(imgID) + " to file "
                    + imgFile.toAbsolutePath() + ".", ioException);
        } else {
            log.warn("An exception was thrown during image creation with ID " + String.valueOf(imgID) + " to file "
                    + imgFile.toAbsolutePath() + ".", ioException);
        }
    }

    nrOfImagesGenerated.incrementAndGet();
}
项目:elasticsearch_my    文件:ClientYamlTestSuite.java   
public static ClientYamlTestSuite parse(String api, Path file) throws IOException {
    if (!Files.isRegularFile(file)) {
        throw new IllegalArgumentException(file.toAbsolutePath() + " is not a file");
    }

    String filename = file.getFileName().toString();
    //remove the file extension
    int i = filename.lastIndexOf('.');
    if (i > 0) {
        filename = filename.substring(0, i);
    }

    //our yaml parser seems to be too tolerant. Each yaml suite must end with \n, otherwise clients tests might break.
    try (FileChannel channel = FileChannel.open(file, StandardOpenOption.READ)) {
        ByteBuffer bb = ByteBuffer.wrap(new byte[1]);
        channel.read(bb, channel.size() - 1);
        if (bb.get(0) != 10) {
            throw new IOException("test suite [" + api + "/" + filename + "] doesn't end with line feed (\\n)");
        }
    }

    try (XContentParser parser = YamlXContent.yamlXContent.createParser(ExecutableSection.XCONTENT_REGISTRY,
            Files.newInputStream(file))) {
        return parse(api, filename, parser);
    } catch(Exception e) {
        throw new IOException("Error parsing " + api + "/" + filename, e);
    }
}
项目:authlib-injector    文件:ClassTransformer.java   
private void saveClassFile(String className, byte[] classBuffer) {
    try {
        Files.write(Paths.get(className + "_dump.class"), classBuffer, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
    } catch (IOException e) {
        log("unable to dump class {0}: {1}", className, e);
        e.printStackTrace();
    }
}
项目:elasticsearch_my    文件:TruncateTranslogCommand.java   
/**
 * Write a translog containing the given translog UUID to the given location. Returns the number of bytes written.
 */
public static int writeEmptyTranslog(Path filename, String translogUUID) throws IOException {
    final BytesRef translogRef = new BytesRef(translogUUID);
    try (FileChannel fc = FileChannel.open(filename, StandardOpenOption.WRITE, StandardOpenOption.READ, StandardOpenOption.CREATE_NEW);
            OutputStreamDataOutput out = new OutputStreamDataOutput(Channels.newOutputStream(fc))) {
        TranslogWriter.writeHeader(out, translogRef);
        fc.force(true);
    }
    return TranslogWriter.getHeaderLength(translogRef.length);
}