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


Java FileChannel.open方法代码示例

本文整理汇总了Java中java.nio.channels.FileChannel.open方法的典型用法代码示例。如果您正苦于以下问题:Java FileChannel.open方法的具体用法?Java FileChannel.open怎么用?Java FileChannel.open使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.nio.channels.FileChannel的用法示例。


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

示例1: mismatchingRevision

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
@Test
public void mismatchingRevision() throws Exception {
    db.close();

    // Append a record with incorrect revision number.
    try (FileChannel f = FileChannel.open(new File(tmpDir.getRoot(), "commit_ids.dat").toPath(),
                                          StandardOpenOption.APPEND)) {

        final ByteBuffer buf = ByteBuffer.allocate(24);
        buf.putInt(42); // Expected to be 1.
        randomCommitId().copyRawTo(buf);
        buf.flip();
        do {
            f.write(buf);
        } while (buf.hasRemaining());

        assertThat(f.size()).isEqualTo(buf.capacity());
    }

    // Reopen the database and see if it fails to resolve the revision 1.
    db = new CommitIdDatabase(tmpDir.getRoot());
    assertThatThrownBy(() -> db.get(Revision.INIT))
            .isInstanceOf(StorageException.class)
            .hasMessageContaining("incorrect revision number");
}
 
开发者ID:line,项目名称:centraldogma,代码行数:26,代码来源:CommitIdDatabaseTest.java

示例2: shouldLockTaskStateDirectory

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
@Test
public void shouldLockTaskStateDirectory() throws Exception {
    final TaskId taskId = new TaskId(0, 0);
    final File taskDirectory = directory.directoryForTask(taskId);

    directory.lock(taskId, 0);

    try (
        final FileChannel channel = FileChannel.open(
            new File(taskDirectory, StateDirectory.LOCK_FILE_NAME).toPath(),
            StandardOpenOption.CREATE, StandardOpenOption.WRITE)
    ) {
        channel.tryLock();
        fail("shouldn't be able to lock already locked directory");
    } catch (final OverlappingFileLockException e) {
        // pass
    } finally {
        directory.unlock(taskId);
    }
}
 
开发者ID:YMCoding,项目名称:kafka-0.11.0.0-src-with-comment,代码行数:21,代码来源:StateDirectoryTest.java

示例3: main

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
public static void main(String[] args) throws Throwable {
    try (FileChannel ch = FileChannel.open(BLK_PATH, READ);
         RandomAccessFile file = new RandomAccessFile(BLK_FNAME, "r")) {

        long size1 = ch.size();
        long size2 = file.length();
        if (size1 != size2) {
            throw new RuntimeException("size differs when retrieved" +
                    " in different ways: " + size1 + " != " + size2);
        }
        System.out.println("OK");

    } catch (NoSuchFileException nsfe) {
        System.err.println("File " + BLK_FNAME + " not found." +
                " Skipping test");
    } catch (AccessDeniedException ade) {
        System.err.println("Access to " + BLK_FNAME + " is denied." +
                " Run test as root.");
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:21,代码来源:BlockDeviceSize.java

示例4: truncatedDatabase

import java.nio.channels.FileChannel; //导入方法依赖的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

示例5: writeToLocal

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
public Location writeToLocal(BytesReference data) throws IOException {
    final long position;
    final long generation;
    try (ReleasableLock lock = writeLock.acquire()) {
        ensureOpen();
        if (writtenOffset > TRANSLOG_ROLLING_SIZE_BYTES) {
            IOUtils.close(writeChannel);
            tmpTranslogGeneration.incrementAndGet();
            writeChannel = FileChannel.open(this.translogPath.resolve(getFileNameFromId(tmpTranslogGeneration.get())), StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
            writtenOffset = 0;
        }
        generation = tmpTranslogGeneration.get();
        position = writtenOffset;
        try {
            data.writeTo(writeChannel);
        } catch (Throwable e) {
            throw e;
        }
        writtenOffset = writtenOffset + data.length();
    }
    return new Translog.Location(generation, position, data.length());
}
 
开发者ID:baidu,项目名称:Elasticsearch,代码行数:23,代码来源:LocalTranslog.java

示例6: corruptTranslogs

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
 * Randomly overwrite some bytes in the translog files
 */
private void corruptTranslogs(Path directory) throws Exception {
    Path[] files = FileSystemUtils.files(directory, "translog-*");
    for (Path file : files) {
        logger.info("--> corrupting {}...", file);
        FileChannel f = FileChannel.open(file, StandardOpenOption.READ, StandardOpenOption.WRITE);
        int corruptions = scaledRandomIntBetween(10, 50);
        for (int i = 0; i < corruptions; i++) {
            // note: with the current logic, this will sometimes be a no-op
            long pos = randomIntBetween(0, (int) f.size());
            ByteBuffer junk = ByteBuffer.wrap(new byte[]{randomByte()});
            f.write(junk, pos);
        }
        f.close();
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:19,代码来源:TranslogTests.java

示例7: applyXOR

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
public static void applyXOR(Path assemblyFile, long limit) throws URISyntaxException, IOException {
	Path inputFile = assemblyFile.resolveSibling(DLL_NAME + ".bak");
	URI xorUri = FileUtils.class.getResource("/" + XOR_NAME).toURI();

	Files.move(assemblyFile, inputFile, StandardCopyOption.REPLACE_EXISTING);

	try (FileSystem fileSystem = createFileSystem(xorUri); // Required to resolve xorUri
	     FileChannel inputChannel = FileChannel.open(inputFile, READ);
	     FileChannel xorChannel = FileChannel.open(Paths.get(xorUri), READ);
	     FileChannel outputChannel = FileChannel.open(assemblyFile, WRITE, CREATE_NEW)) {

		xorFiles(inputChannel, xorChannel, outputChannel, limit);
	} catch (Throwable t) {
		Files.deleteIfExists(assemblyFile);
		Files.move(inputFile, assemblyFile);
		throw t;
	}
}
 
开发者ID:zeobviouslyfakeacc,项目名称:ModLoaderInstaller,代码行数:19,代码来源:FileUtils.java

示例8: read

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
@Override
public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
    try {
        final FileChannel channel = FileChannel.open(session.toPath(file), StandardOpenOption.READ);
        channel.position(status.getOffset());
        return Channels.newInputStream(channel);
    }
    catch(IOException e) {
        throw new LocalExceptionMappingService().map("Download {0} failed", e, file);
    }
}
 
开发者ID:iterate-ch,项目名称:cyberduck,代码行数:12,代码来源:LocalReadFeature.java

示例9: onSubscribe

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
@Override
public void onSubscribe(Flow.Subscription subscription) {
    this.subscription = subscription;
    try {
        out = FileChannel.open(file, options);
    } catch (IOException e) {
        result.completeExceptionally(e);
        subscription.cancel();
        return;
    }
    subscription.request(1);
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:13,代码来源:ResponseProcessors.java

示例10: uploadChunk

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
public Observable<Long> uploadChunk(TusRequest request) {
    if (uploadInProgress.compareAndSet(false, true)) {
        refreshTimer();
        try {
            FileChannel fChannel = FileChannel.open(
                    rootDir.resolve(uuid.toString()).resolve("chunk-" + offset.get()),
                    new StandardOpenOption[] { StandardOpenOption.CREATE, StandardOpenOption.WRITE });

            return request.getContent().doOnNext(bb -> logger.debug("received some ByteBuffer"))
                    .buffer(100, TimeUnit.MILLISECONDS)
                    .filter(bb -> bb.size() > 0)
                    .flatMap(bb -> Observable.fromCallable(() -> {
                        logger.debug("writing " + bb.size() + " buffers  to file");
                        return fChannel.write(bb.toArray(new ByteBuffer[bb.size()]));
                    }).observeOn(Schedulers.io()))
                    .doOnError(x -> {
                        logger.error("something went wrong, cleaning up", x);
                        uploadInProgress.set(false);
                        cleanup(fChannel);
                    })
                    .doOnCompleted(() -> {
                        logger.debug("cool bro, it is done, cleaning up");
                        uploadInProgress.set(false);
                        cleanup(fChannel);
                    });
        } catch (IOException e1) {
            return Observable.error(e1);
        }
    } else {
        return Observable.error(new ChunkAlreadyUploadingException());
    }
}
 
开发者ID:jerbome,项目名称:tusRx,代码行数:33,代码来源:TusUpload.java

示例11: newFileChannel

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
static FileChannel newFileChannel(File file) throws IOException {
    if (rand.nextBoolean()) {
        return new FileOutputStream(file, true).getChannel();
    } else {
        return FileChannel.open(file.toPath(), APPEND);
    }
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:8,代码来源:AtomicAppend.java

示例12: main

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
public static void main(String[] args) throws Exception {
    Path blah = Files.createTempFile("blah", null);
    blah.toFile().deleteOnExit();
    initTestFile(blah);

    for (int i=0; i<10; i++) {
        try (FileChannel fc = (generator.nextBoolean()) ?
                FileChannel.open(blah, READ) :
                new FileInputStream(blah.toFile()).getChannel()) {
            for (int j=0; j<100; j++) {
                long newPos = generator.nextInt(1000);
                fc.position(newPos);
                if (fc.position() != newPos)
                    throw new RuntimeException("Position failed");
            }
        }
    }

    for (int i=0; i<10; i++) {
        try (FileChannel fc = (generator.nextBoolean()) ?
                 FileChannel.open(blah, APPEND) :
                 new FileOutputStream(blah.toFile(), true).getChannel()) {
            for (int j=0; j<10; j++) {
                if (fc.position() != fc.size())
                    throw new RuntimeException("Position expected to be size");
                byte[] buf = new byte[generator.nextInt(100)];
                fc.write(ByteBuffer.wrap(buf));
            }
        }
    }

    Files.delete(blah);
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:34,代码来源:Position.java

示例13: beforeAll

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
@BeforeAll
void beforeAll() throws IOException {
    file = FileGenerator.randomTempFile(1024);
    fc = FileChannel.open(file.path, StandardOpenOption.READ);
    defaultAmazonS3().putObject(testBucket, key, file.path.toFile());
    s3Channel = S3ReadableObjectChannel.builder()
            .amazonS3(defaultAmazonS3())
            .bucket(testBucket)
            .key(key)
            .build();
    assertEquals(s3Channel.size(), 1024);
}
 
开发者ID:mentegy,项目名称:s3-channels,代码行数:13,代码来源:S3RangedReadObjectChannelTest.java

示例14: concat

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
private void concat(final Path baseFolder, List<Path> paths) throws IOException {
    final Path outFile = Paths.get(baseFolder.toString(), FRAGMENT_FOLDER, UUID.randomUUID() + FRAGMENT_POSTFIX);
    try (FileChannel out = FileChannel.open(outFile, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE)) {
        for (Path part : paths) {
            transferPart(out, part);
        }
    }
    for (Path path : paths) {
        Files.delete(path);
    }
}
 
开发者ID:MinBZK,项目名称:OperatieBRP,代码行数:12,代码来源:SelectieFileServiceImpl.java

示例15: init

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
@Override
public void init() throws IOException {
	approversChannel = FileChannel.open(Paths.get(APPROVERS_FILE_NAME), 
			StandardOpenOption.CREATE, StandardOpenOption.READ, StandardOpenOption.WRITE);
	
	approversChunks[0] = approversChannel.map(FileChannel.MapMode.READ_WRITE, 0, SUPER_GROUPS_SIZE);
	final long approversChannelSize = approversChannel.size();
	while (true) {

		if ((approversNextPointer & (CHUNK_SIZE - 1)) == 0) {
			approversChunks[(int) (approversNextPointer >> 27)] = approversChannel
			        .map(FileChannel.MapMode.READ_WRITE, approversNextPointer, CHUNK_SIZE);
		}
		if (approversChannelSize - approversNextPointer > CHUNK_SIZE) {
			approversNextPointer += CHUNK_SIZE;
		} else {
			approversChunks[(int) (approversNextPointer >> 27)].get(mainBuffer);
			boolean empty = true;
			for (final int value : mainBuffer) {

				if (value != 0) {
					empty = false;
					break;
				}
			}
			if (empty) {
				break;
			}
			approversNextPointer += CELL_SIZE;
		}
	}
}
 
开发者ID:AidosKuneen,项目名称:aidos-node,代码行数:33,代码来源:StorageApprovers.java


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