当前位置: 首页>>代码示例>>Java>>正文


Java StandardOpenOption类代码示例

本文整理汇总了Java中java.nio.file.StandardOpenOption的典型用法代码示例。如果您正苦于以下问题:Java StandardOpenOption类的具体用法?Java StandardOpenOption怎么用?Java StandardOpenOption使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


StandardOpenOption类属于java.nio.file包,在下文中一共展示了StandardOpenOption类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: openReader

import java.nio.file.StandardOpenOption; //导入依赖的package包/类
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;
    }
}
 
开发者ID:baidu,项目名称:Elasticsearch,代码行数:24,代码来源:LocalTranslog.java

示例2: SharedSystemData

import java.nio.file.StandardOpenOption; //导入依赖的package包/类
/**
 * 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);
	}
}
 
开发者ID:bizzard4,项目名称:MpiTaskFramework,代码行数:27,代码来源:SharedSystemData.java

示例3: followFile

import java.nio.file.StandardOpenOption; //导入依赖的package包/类
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));
    }
}
 
开发者ID:DevOpsStudio,项目名称:Re-Collector,代码行数:17,代码来源:ChunkReaderScheduler.java

示例4: initialize

import java.nio.file.StandardOpenOption; //导入依赖的package包/类
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();
    }
}
 
开发者ID:NexusByte,项目名称:LotusCloud,代码行数:18,代码来源:Database.java

示例5: download

import java.nio.file.StandardOpenOption; //导入依赖的package包/类
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));
    }
 
开发者ID:LoopPerfect,项目名称:buckaroo,代码行数:21,代码来源:DownloadTask.java

示例6: should_find_local_newly_staged_files_as_new

import java.nio.file.StandardOpenOption; //导入依赖的package包/类
@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");
}
 
开发者ID:arquillian,项目名称:smart-testing,代码行数:21,代码来源:NewTestsGitBasedDetectorTest.java

示例7: generate

import java.nio.file.StandardOpenOption; //导入依赖的package包/类
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();
  }
}
 
开发者ID:inferjay,项目名称:r8,代码行数:25,代码来源:JumboString.java

示例8: fuseOpenFlagsToNioOpenOptions

import java.nio.file.StandardOpenOption; //导入依赖的package包/类
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;
}
 
开发者ID:cryptomator,项目名称:fuse-nio-adapter,代码行数:17,代码来源:OpenOptionsUtil.java

示例9: shouldReleaseTaskStateDirectoryLock

import java.nio.file.StandardOpenOption; //导入依赖的package包/类
@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();
    }
}
 
开发者ID:YMCoding,项目名称:kafka-0.11.0.0-src-with-comment,代码行数:18,代码来源:StateDirectoryTest.java

示例10: shouldWorkWithApplicationPropertiesFormOtherLocation

import java.nio.file.StandardOpenOption; //导入依赖的package包/类
@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();
    }
}
 
开发者ID:drinkwater-io,项目名称:drinkwater-java,代码行数:26,代码来源:PropertiesTest.java

示例11: testReleaseClosesOpenFileChannel

import java.nio.file.StandardOpenOption; //导入依赖的package包/类
@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);
}
 
开发者ID:tfiskgul,项目名称:mux2fs,代码行数:19,代码来源:MirrorFsTest.java

示例12: withTempInput

import java.nio.file.StandardOpenOption; //导入依赖的package包/类
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);
        }
    }
}
 
开发者ID:openshift,项目名称:jenkins-client-plugin,代码行数:21,代码来源:BaseStep.java

示例13: unpack

import java.nio.file.StandardOpenOption; //导入依赖的package包/类
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();   
    }
}
 
开发者ID:Alfresco,项目名称:alfresco-repository,代码行数:20,代码来源:BulkImportTest.java

示例14: listsFiles

import java.nio.file.StandardOpenOption; //导入依赖的package包/类
@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))
    );
}
 
开发者ID:yegor256,项目名称:jpeek,代码行数:18,代码来源:DefaultBaseTest.java

示例15: truncatedDatabase

import java.nio.file.StandardOpenOption; //导入依赖的package包/类
@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");
}
 
开发者ID:line,项目名称:centraldogma,代码行数:18,代码来源:CommitIdDatabaseTest.java


注:本文中的java.nio.file.StandardOpenOption类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。