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


Java ByteSink类代码示例

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


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

示例1: saveTo

import com.google.common.io.ByteSink; //导入依赖的package包/类
public void saveTo(ByteSink sink) throws IOException {
  final PrintWriter out = new PrintWriter(sink.asCharSink(Charsets.UTF_8).openBufferedStream());

  out.println(docIdToBannedRegions.size());

  for (final Map.Entry<Symbol, ImmutableRangeSet<Integer>> entry : docIdToBannedRegions
      .entrySet()) {
    out.println(entry.getKey());
    final List<String> parts = Lists.newArrayList();
    for (final Range<Integer> r : entry.getValue().asRanges()) {
      // we know by construction these ranges are bounded above and below
      parts.add(String.format("%d-%d", r.lowerEndpoint(), r.upperEndpoint()));
    }
    out.println(StringUtils.SpaceJoiner.join(parts));
  }

  out.close();
}
 
开发者ID:isi-nlp,项目名称:tac-kbp-eal,代码行数:19,代码来源:QuoteFilter.java

示例2: testGet_io

import com.google.common.io.ByteSink; //导入依赖的package包/类
public void testGet_io() throws IOException {
  assertEquals(-1, ArbitraryInstances.get(InputStream.class).read());
  assertEquals(-1, ArbitraryInstances.get(ByteArrayInputStream.class).read());
  assertEquals(-1, ArbitraryInstances.get(Readable.class).read(CharBuffer.allocate(1)));
  assertEquals(-1, ArbitraryInstances.get(Reader.class).read());
  assertEquals(-1, ArbitraryInstances.get(StringReader.class).read());
  assertEquals(0, ArbitraryInstances.get(Buffer.class).capacity());
  assertEquals(0, ArbitraryInstances.get(CharBuffer.class).capacity());
  assertEquals(0, ArbitraryInstances.get(ByteBuffer.class).capacity());
  assertEquals(0, ArbitraryInstances.get(ShortBuffer.class).capacity());
  assertEquals(0, ArbitraryInstances.get(IntBuffer.class).capacity());
  assertEquals(0, ArbitraryInstances.get(LongBuffer.class).capacity());
  assertEquals(0, ArbitraryInstances.get(FloatBuffer.class).capacity());
  assertEquals(0, ArbitraryInstances.get(DoubleBuffer.class).capacity());
  ArbitraryInstances.get(PrintStream.class).println("test");
  ArbitraryInstances.get(PrintWriter.class).println("test");
  assertNotNull(ArbitraryInstances.get(File.class));
  assertFreshInstanceReturned(
      ByteArrayOutputStream.class, OutputStream.class,
      Writer.class, StringWriter.class,
      PrintStream.class, PrintWriter.class);
  assertEquals(ByteSource.empty(), ArbitraryInstances.get(ByteSource.class));
  assertEquals(CharSource.empty(), ArbitraryInstances.get(CharSource.class));
  assertNotNull(ArbitraryInstances.get(ByteSink.class));
  assertNotNull(ArbitraryInstances.get(CharSink.class));
}
 
开发者ID:zugzug90,项目名称:guava-mock,代码行数:27,代码来源:ArbitraryInstancesTest.java

示例3: writeFile

import com.google.common.io.ByteSink; //导入依赖的package包/类
public static Single<WriteFileEvent> writeFile(final String content, final Path path, final boolean overwrite) {
    Preconditions.checkNotNull(content);
    Preconditions.checkNotNull(path);
    return Single.fromCallable(() -> {
        if (path.getParent() != null && !Files.exists(path.getParent())) {
            Files.createDirectories(path.getParent());
        }
        if (overwrite) {
            Files.deleteIfExists(path);
        } else if (Files.isDirectory(path)) {
            throw new IOException("There is already a directory at " + path);
        } else if (Files.exists(path)) {
            throw new IOException("There is already a file at " + path);
        }
        final ByteSink sink = MoreFiles.asByteSink(path);
        sink.write(content.getBytes());
        return WriteFileEvent.of(path);
    }).subscribeOn(Schedulers.io());
}
 
开发者ID:LoopPerfect,项目名称:buckaroo,代码行数:20,代码来源:CommonTasks.java

示例4: runScenario

import com.google.common.io.ByteSink; //导入依赖的package包/类
private static void runScenario( final Class<? extends Scenario> scenarioClass ) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, IOException, InterruptedException, ExecutionException {

		final File scenarioOutputFile = new File(
				TARGET_DIRECTORY,
				scenarioClass.getCanonicalName()
		);

		final ScenarioRunner scenarioRunner = new ScenarioRunner(
				scenarioClass,
				new ByteSink() {
					@Override
					public OutputStream openStream() throws IOException {
						final ByteSink fileSink = Files.asByteSink( scenarioOutputFile );
						return new MultiplexingOutputStream(
								System.out,
								fileSink.openStream()
						);
					}
				},
				EXTENDED_RUN_PARAMETERS
		);

		scenarioRunner.run();
	}
 
开发者ID:cheremin,项目名称:scalarization,代码行数:25,代码来源:ForkingMain.java

示例5: getOutput

import com.google.common.io.ByteSink; //导入依赖的package包/类
/**
 * Returns a byte sink for generating output. If the name is "-" then bytes will go to the standard output
 * stream, otherwise name is taken as a file path relative to the current working directory.
 */
protected static ByteSink getOutput(String name) {
    try {
        if (name.equals("-")) {
            return new ByteSink() {
                @Override
                public OutputStream openStream() throws IOException {
                    // TODO Block closing?
                    return System.out;
                }
            };
        } else {
            File file = new File(name);
            if (file.isDirectory()) {
                throw new IOException(name); // TODO Message? Exception?
            } else if (file.exists() && !file.canWrite()) {
                throw new IOException(name); // TODO Message? Exception?
            } else {
                return Files.asByteSink(file);
            }
        }
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
开发者ID:blackducksoftware,项目名称:bdio,代码行数:29,代码来源:Tool.java

示例6: finish

import com.google.common.io.ByteSink; //导入依赖的package包/类
@Override
public void finish() throws IOException {
  final CharSink textSink = Files.asCharSink(new File(outputDir, outputName + FILE_SUFFIX),
      Charsets.UTF_8);
  final ByteSink jsonSink = Files.asByteSink(new File(outputDir, outputName + FILE_SUFFIX + ".json"));

  final SummaryConfusionMatrix summaryConfusionMatrix = summaryConfusionMatrixB.build();
  // Output the summaries and add a final newline
  final FMeasureCounts fMeasure =
      SummaryConfusionMatrices.FMeasureVsAllOthers(summaryConfusionMatrix, PRESENT);
  textSink.write(StringUtils.NewlineJoiner.join(
      SummaryConfusionMatrices.prettyPrint(summaryConfusionMatrix),
      fMeasure.compactPrettyString(),
      ""));  // Empty string creates a bare newline at the end
  JacksonSerializer.builder().forJson().prettyOutput().build().serializeTo(fMeasure, jsonSink);

  // Call finish on the observers
  for (final ScoringEventObserver observer : scoringEventObservers) {
    observer.finish(outputDir);
  }
}
 
开发者ID:BBN-E,项目名称:bue-common-open,代码行数:22,代码来源:AggregateBinaryFScoresInspector.java

示例7: writeBinary

import com.google.common.io.ByteSink; //导入依赖的package包/类
public static void writeBinary(OffsetIndex offsetIndex, ByteSink sink) throws IOException {
  final DataOutputStream out = new DataOutputStream(sink.openBufferedStream());

  boolean threw = true;
  try {
    out.writeInt(offsetIndex.keySet().size());
    // use a fixed key order to be diff-friendly.
    final Iterable<Symbol> keyOrder =
        Ordering.usingToString().immutableSortedCopy(offsetIndex.keySet());
    for (final Symbol key : keyOrder) {
      out.writeUTF(key.asString());
      // get is safe because we are iterating over the mapping's key set
      final OffsetRange<ByteOffset> range = offsetIndex.byteOffsetsOf(key).get();
      out.writeInt(range.startInclusive().asInt());
      out.writeInt(range.endInclusive().asInt());
    }
    threw = false;
  } finally {
    Closeables.close(out, threw);
  }

}
 
开发者ID:BBN-E,项目名称:bue-common-open,代码行数:23,代码来源:OffsetIndices.java

示例8: compileToJar

import com.google.common.io.ByteSink; //导入依赖的package包/类
/**
 * Compiles all the templates in the given registry to a jar file written to the given output
 * stream.
 *
 * <p>If errors are encountered, the error reporter will be updated and we will return. The
 * contents of any data written to the sink at that point are undefined.
 *
 * @param registry All the templates to compile
 * @param reporter The error reporter
 * @param sink The output sink to write the JAR to.
 */
public static void compileToJar(TemplateRegistry registry, ErrorReporter reporter, ByteSink sink)
    throws IOException {
  ErrorReporter.Checkpoint checkpoint = reporter.checkpoint();
  if (reporter.errorsSince(checkpoint)) {
    return;
  }
  CompiledTemplateRegistry compilerRegistry = new CompiledTemplateRegistry(registry);
  if (reporter.errorsSince(checkpoint)) {
    return;
  }
  try (final SoyJarFileWriter writer = new SoyJarFileWriter(sink.openStream())) {
    compileTemplates(
        compilerRegistry,
        reporter,
        new CompilerListener<Void>() {
          @Override
          void onCompile(ClassData clazz) throws IOException {
            writer.writeEntry(
                clazz.type().internalName() + ".class", ByteSource.wrap(clazz.data()));
          }
        });
  }
}
 
开发者ID:google,项目名称:closure-templates,代码行数:35,代码来源:BytecodeCompiler.java

示例9: writeSrcJar

import com.google.common.io.ByteSink; //导入依赖的package包/类
/**
 * Writes the source files out to a {@code -src.jar}. This places the soy files at the same
 * classpath relative location as their generated classes. Ultimately this can be used by
 * debuggers for source level debugging.
 *
 * <p>It is a little weird that the relative locations of the generated classes are not identical
 * to the input source files. This is due to the disconnect between java packages and soy
 * namespaces. We should consider using the soy namespace directly as a java package in the
 * future.
 *
 * @param registry All the templates in the current compilation unit
 * @param files The source files by file path
 * @param sink The source to write the jar file
 */
public static void writeSrcJar(
    TemplateRegistry registry, ImmutableMap<String, SoyFileSupplier> files, ByteSink sink)
    throws IOException {
  Set<SoyFileNode> seenFiles = new HashSet<>();
  try (SoyJarFileWriter writer = new SoyJarFileWriter(sink.openStream())) {
    for (TemplateNode template : registry.getAllTemplates()) {
      SoyFileNode file = template.getParent();
      if (file.getSoyFileKind() == SoyFileKind.SRC && seenFiles.add(file)) {
        String namespace = file.getNamespace();
        String fileName = file.getFileName();
        writer.writeEntry(
            Names.javaFileName(namespace, fileName),
            files.get(file.getFilePath()).asCharSource().asByteSource(UTF_8));
      }
    }
  }
}
 
开发者ID:google,项目名称:closure-templates,代码行数:32,代码来源:BytecodeCompiler.java

示例10: saveStream

import com.google.common.io.ByteSink; //导入依赖的package包/类
/**
 * Save the content of a NBT compound to a stream.
 *
 * @param source - the NBT compound to save.
 * @param stream - the stream.
 * @param option - whether or not to compress the output.
 * @throws IOException If anything went wrong.
 */
public static void saveStream(NbtCompound source, ByteSink stream, StreamOptions option) throws IOException {
    OutputStream output = null;
    DataOutputStream data = null;
    boolean suppress = true;

    try {
        output = stream.openStream();
        data = new DataOutputStream(option == StreamOptions.GZIP_COMPRESSION ? new GZIPOutputStream(output) : output);

        invokeMethod(get().SAVE_COMPOUND, null, source.getHandle(), data);
        suppress = false;

    } finally {
        if (data != null) {
            Closeables.close(data, suppress);
        } else if (output != null) {
            Closeables.close(output, suppress);
        }
    }
}
 
开发者ID:IntellectualSites,项目名称:PlotSquared,代码行数:29,代码来源:NbtFactory.java

示例11: writeArray

import com.google.common.io.ByteSink; //导入依赖的package包/类
private void writeArray(DoubleArrayList numbers, File file) throws IOException {
  final ByteSink sink = GZIPByteSink.gzipCompress(Files.asByteSink(file));
  final PrintWriter out = new PrintWriter(sink.asCharSink(Charsets.UTF_8).openBufferedStream());
  for (final DoubleCursor cursor : numbers) {
    out.println(cursor.value);
  }
  out.close();
  ;
}
 
开发者ID:isi-nlp,项目名称:tac-kbp-eal,代码行数:10,代码来源:EAScoringObserver.java

示例12: ScenarioRunner

import com.google.common.io.ByteSink; //导入依赖的package包/类
public ScenarioRunner( final Class<? extends Scenario> scenarioClass,
                       final ByteSink reportTo,
                       final ScenarioRun[] extendedRunArguments ) throws IllegalAccessException, InstantiationException {
	checkArgument( scenarioClass != null, "scenarioClass can't be null" );
	checkArgument( reportTo != null, "reportTo can't be null" );

	//just to check class have 0-arg ctor and can be cast to Scenario
	final Scenario scenario = scenarioClass.newInstance();


	this.scenarioClass = scenarioClass;
	this.reportTo = reportTo;
	this.extendedRunArguments = extendedRunArguments;
}
 
开发者ID:cheremin,项目名称:scalarization,代码行数:15,代码来源:ScenarioRunner.java

示例13: stream

import com.google.common.io.ByteSink; //导入依赖的package包/类
final void stream(
    ByteSource input, ByteSink output, ByteSink error)
throws IOException, MojoExecutionException {
  try (InputStream in = input.openBufferedStream()) {
    try (OutputStream out = output.openBufferedStream()) {
      try (PrintStream pout = new PrintStream(out, true, "UTF-8")) {
        try (OutputStream err = error.openBufferedStream()) {
          try (PrintStream perr = new PrintStream(err, true, "UTF-8")) {
            stream(in, pout, perr);
          }
        }
      }
    }
  }
}
 
开发者ID:mikesamuel,项目名称:closure-maven-plugin,代码行数:16,代码来源:Streamer.java

示例14: copyToByteSinkTest

import com.google.common.io.ByteSink; //导入依赖的package包/类
@Test
public void copyToByteSinkTest() throws Exception {
    File dest = new File("src/test/resources/sampleCompany.pdf");
    dest.deleteOnExit();
    File source = new File("src/main/resources/sample.pdf");
    ByteSource byteSource = Files.asByteSource(source);
    ByteSink byteSink = Files.asByteSink(dest);
    byteSource.copyTo(byteSink);
    assertThat(Files.toByteArray(dest), is(Files.toByteArray(source)));
}
 
开发者ID:wsldl123292,项目名称:testeverything,代码行数:11,代码来源:ByteSourceTest.java

示例15: toTmpKeyStoreFile

import com.google.common.io.ByteSink; //导入依赖的package包/类
/**
 * Creates a new keystore that will contain a single entry with given {@code entryAlias} and {@code entryPassword}
 * and stores it to a temporary file. The entry will contain the private key and the certificate.
 */
public File toTmpKeyStoreFile(String entryAlias, String password) throws IOException, GeneralSecurityException {
    KeyStore keyStore = toKeyStore(entryAlias, password);
    File keyStoreFile = File.createTempFile("key-" + entryAlias, ".keystore", new File("target"));
    ByteSink keyStoreSink = Files.asByteSink(keyStoreFile);
    OutputStream keyStoreStream = keyStoreSink.openStream();

    try {
        keyStore.store(keyStoreStream, password.toCharArray());
    } finally {
        Closeables.close(keyStoreStream, true);
    }

    return keyStoreFile;
}
 
开发者ID:wildfly-extras,项目名称:creaper,代码行数:19,代码来源:KeyPairAndCertificate.java


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