类com.google.common.io.CharSink源码实例Demo

下面列出了怎么用com.google.common.io.CharSink的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: google-ads-java   文件: MethodsListGenerator.java
public static void main(String args[])
    throws ClassNotFoundException, IOException, NoSuchMethodException {
  Method latestVersionMethod = GoogleAdsAllVersions.class.getMethod("getLatestVersion");
  Class cls = Class.forName(latestVersionMethod.getReturnType().getName());
  List<Method> methods = Arrays.asList(cls.getDeclaredMethods());

  StringBuilder output = new StringBuilder();
  for (Method method : methods) {
    output.append(method + "\n");
  }

  System.out.println("Writing the following methods to file:");
  System.out.printf(output.toString());

  File file = new File("./google-ads/src/test/resources/testdata/avail_service_clients.txt");
  CharSink sink = Files.asCharSink(file, Charsets.UTF_8);
  sink.write(output);
}
 
源代码2 项目: tac-kbp-eal   文件: DefaultCorpusQueryWriter.java
@Override
public void writeQueries(final CorpusQuerySet2016 queries,
    final CharSink sink) throws IOException {
  final StringBuilder sb = new StringBuilder();

  int numEntryPoints = 0;
  for (final CorpusQuery2016 query : QUERY_ORDERING.sortedCopy(queries)) {
    for (final CorpusQueryEntryPoint entryPoint : ENTRY_POINT_ORDERING
        .sortedCopy(query.entryPoints())) {
      sb.append(entryPointString(query, entryPoint)).append("\n");
      ++numEntryPoints;
    }
  }
  log.info("Writing {} queries with {} entry points to {}", queries.queries().size(),
      numEntryPoints, sink);
  sink.write(sb.toString());
}
 
源代码3 项目: tac-kbp-eal   文件: CorpusEventFrameWriter2016.java
@Override
public void writeCorpusEventFrames(final CorpusEventLinking corpusEventLinking,
    final CharSink sink) throws IOException {
  checkArgument(noneEqualForHashable(FluentIterable.from(corpusEventLinking.corpusEventFrames())
      .transform(id())));

  try (Writer writer = sink.openBufferedStream()) {
    for (final CorpusEventFrame corpusEventFrame : BY_ID
        .sortedCopy(corpusEventLinking.corpusEventFrames())) {
      final List<DocEventFrameReference> sortedDocEventFrames =
          DocEventFrameReference.canonicalOrdering()
              .sortedCopy(corpusEventFrame.docEventFrames());
      writer.write(
          corpusEventFrame.id()
              + "\t"
              + FluentIterable.from(sortedDocEventFrames)
              .transform(canonicalStringFunction())
              .join(SPACE_JOINER)
              + "\n");
    }
  }
}
 
源代码4 项目: tutorials   文件: JavaXToWriterUnitTest.java
@Test
public void givenUsingGuava_whenConvertingByteArrayIntoWriter_thenCorrect() throws IOException {
    final byte[] initialArray = "With Guava".getBytes();

    final String buffer = new String(initialArray);
    final StringWriter stringWriter = new StringWriter();
    final CharSink charSink = new CharSink() {
        @Override
        public final Writer openStream() throws IOException {
            return stringWriter;
        }
    };
    charSink.write(buffer);

    stringWriter.close();

    assertEquals("With Guava", stringWriter.toString());
}
 
源代码5 项目: java-n-IDE-for-Android   文件: Formatter.java
/**
 * Format the given input (a Java compilation unit) into the output stream.
 *
 * @throws FormatterException if the input cannot be parsed
 */
public void formatSource(CharSource input, CharSink output)
        throws FormatterException, IOException {
    // TODO(cushon): proper support for streaming input/output. Input may
    // not be feasible (parsing) but output should be easier.
    output.write(formatSource(input.read()));
}
 
@Override
public Writer openWriter() throws IOException {
  final StringBuilder stringBuilder = new StringBuilder(DEFAULT_FILE_SIZE);
  return new Writer() {
    @Override
    public void write(char[] chars, int start, int end) throws IOException {
      stringBuilder.append(chars, start, end - start);
    }

    @Override
    public void flush() throws IOException {}

    @Override
    public void close() throws IOException {
      try {
        formatter.formatSource(
            CharSource.wrap(stringBuilder),
            new CharSink() {
              @Override
              public Writer openStream() throws IOException {
                return fileObject.openWriter();
              }
            });
      } catch (FormatterException e) {
        // An exception will happen when the code being formatted has an error. It's better to
        // log the exception and emit unformatted code so the developer can view the code which
        // caused a problem.
        try (Writer writer = fileObject.openWriter()) {
          writer.append(stringBuilder.toString());
        }
        if (messager != null) {
          messager.printMessage(Diagnostic.Kind.NOTE, "Error formatting " + getName());
        }
      }
    }
  };
}
 
源代码7 项目: qmq   文件: BatchFileAppender.java
private void writeBatch(final CharSink sink, final List<String> batch) {
    try {
        sink.writeLines(batch);
    } catch (IOException e) {
        LOG.error("write lines failed.", e);
    }
}
 
源代码8 项目: javaide   文件: Formatter.java
/**
 * Format the given input (a Java compilation unit) into the output stream.
 *
 * @throws FormatterException if the input cannot be parsed
 */
public void formatSource(CharSource input, CharSink output)
        throws FormatterException, IOException {
    // TODO(cushon): proper support for streaming input/output. Input may
    // not be feasible (parsing) but output should be easier.
    output.write(formatSource(input.read()));
}
 
源代码9 项目: javaide   文件: FormattingJavaFileObject.java
@Override
public Writer openWriter() throws IOException {
  final StringBuilder stringBuilder = new StringBuilder(DEFAULT_FILE_SIZE);
  return new Writer() {
    @Override
    public void write(char[] chars, int start, int end) throws IOException {
      stringBuilder.append(chars, start, end - start);
    }

    @Override
    public void flush() throws IOException {}

    @Override
    public void close() throws IOException {
      try {
        formatter.formatSource(
            CharSource.wrap(stringBuilder),
            new CharSink() {
              @Override
              public Writer openStream() throws IOException {
                return fileObject.openWriter();
              }
            });
      } catch (FormatterException e) {
        // An exception will happen when the code being formatted has an error. It's better to
        // log the exception and emit unformatted code so the developer can view the code which
        // caused a problem.
        try (Writer writer = fileObject.openWriter()) {
          writer.append(stringBuilder.toString());
        }
        if (messager != null) {
          messager.printMessage(Diagnostic.Kind.NOTE, "Error formatting " + getName());
        }
      }
    }
  };
}
 
源代码10 项目: j2cl   文件: BazelJ2clRta.java
private static void writeToFile(String filePath, List<String> lines) {
  CharSink outputSink = Files.asCharSink(new File(filePath), StandardCharsets.UTF_8);
  try {
    outputSink.writeLines(lines);
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
源代码11 项目: google-java-format   文件: Formatter.java
/**
 * Format the given input (a Java compilation unit) into the output stream.
 *
 * @throws FormatterException if the input cannot be parsed
 */
public void formatSource(CharSource input, CharSink output)
    throws FormatterException, IOException {
  // TODO(cushon): proper support for streaming input/output. Input may
  // not be feasible (parsing) but output should be easier.
  output.write(formatSource(input.read()));
}
 
源代码12 项目: tac-kbp-eal   文件: SingleFileQueryStoreWriter.java
public void saveTo(final CorpusQueryAssessments store, final CharSink sink)
    throws IOException {
  final Writer out = sink.openStream();
  for (final QueryResponse2016 q : by2016Ordering().immutableSortedCopy(store.queryReponses())) {
    final Optional<String> metadata = Optional.fromNullable(store.metadata().get(q));
    if (metadata.isPresent()) {
      out.write("#" + metadata.get() + "\n");
    }
    final QueryAssessment2016 assessment =
        Optional.fromNullable(store.assessments().get(q)).or(QueryAssessment2016.UNASSESSED);

    final ImmutableList.Builder<String> pjStrings = ImmutableList.builder();
    for (final CharOffsetSpan pj : Ordering.natural()
        .immutableSortedCopy(q.predicateJustifications())) {
      pjStrings.add(dashJoiner.join(pj.startInclusive(), pj.endInclusive()));
    }
    final String pjString = commaJoiner.join(pjStrings.build());
    final String systemIDs = StringUtils.commaJoiner()
        .join(FluentIterable.from(store.queryResponsesToSystemIDs().get(q))
            .transform(SymbolUtils.desymbolizeFunction()).toSet());

    final String line =
        tabJoiner.join(q.queryID(), q.docID(), systemIDs, pjString, assessment.name());
    out.write(line + "\n");
  }
  out.close();
}
 
源代码13 项目: tac-kbp-eal   文件: AbstractKBPSpecLinkingWriter.java
@Override
public void write(ResponseLinking responseLinking, CharSink sink) throws IOException {
  final List<String> lines = Lists.newArrayList();
  for (final ResponseSet responseSet : responseLinking.responseSets()) {
    lines.add(renderLine(responseSet, responseLinking));
  }

  // incompletes last
  lines.add("INCOMPLETE\t" + Joiner.on("\t").join(
      transform(responseLinking.incompleteResponses(), ResponseFunctions.uniqueIdentifier())));

  sink.writeLines(lines, "\n");
}
 
源代码14 项目: tac-kbp-eal   文件: KBPAssessmentDiff.java
private static void logCoverage(String leftName, Set<Symbol> leftDocIds, String rightName,
    Set<Symbol> rightDocIds,
    CharSink out) throws IOException {
  final String msg = String.format(
      "%d documents in %s; %d in %s. %d in common, %d left-only, %d right-only",
      leftDocIds.size(), leftName, rightDocIds.size(), rightName,
      Sets.intersection(leftDocIds, rightDocIds).size(),
      Sets.difference(leftDocIds, rightDocIds).size(),
      Sets.difference(rightDocIds, leftDocIds).size());
  log.info(msg);
  out.write(msg);
}
 
源代码15 项目: ipmi4j   文件: IpmiCommandNameTest.java
private void process(Context context, String templateName, String targetPath) throws IOException {
    URL templateUrl = Resources.getResource(IpmiCommandNameTest.class, templateName);
    CharSource source = Resources.asCharSource(templateUrl, StandardCharsets.UTF_8);

    File file = new File(targetPath);
    CharSink sink = Files.asCharSink(file, StandardCharsets.UTF_8);

    try (Reader r = source.openBufferedStream()) {
        try (Writer w = sink.openBufferedStream()) {
            engine.evaluate(context, w, file.getName(), r);
        }
    }
}
 
源代码16 项目: tutorials   文件: GuavaIOUnitTest.java
@Test
public void whenWriteUsingCharSink_thenWritten() throws IOException {
    final String expectedValue = "Hello world";
    final File file = new File("src/test/resources/test.out");
    final CharSink sink = Files.asCharSink(file, Charsets.UTF_8);

    sink.write(expectedValue);

    final String result = Files.toString(file, Charsets.UTF_8);
    assertEquals(expectedValue, result);
}
 
源代码17 项目: tutorials   文件: GuavaIOUnitTest.java
@Test
public void whenWriteMultipleLinesUsingCharSink_thenWritten() throws IOException {
    final List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom");
    final File file = new File("src/test/resources/test.out");
    final CharSink sink = Files.asCharSink(file, Charsets.UTF_8);

    sink.writeLines(names, " ");

    final String result = Files.toString(file, Charsets.UTF_8);
    final String expectedValue = Joiner.on(" ").join(names);
    assertEquals(expectedValue, result.trim());

}
 
源代码18 项目: tutorials   文件: JavaReaderToXUnitTest.java
@Test
public void givenUsingGuava_whenWritingReaderContentsToFile_thenCorrect() throws IOException {
    final Reader initialReader = new StringReader("Some text");

    final File targetFile = new File("src/test/resources/targetFile.txt");
    com.google.common.io.Files.touch(targetFile);
    final CharSink charSink = com.google.common.io.Files.asCharSink(targetFile, Charset.defaultCharset(), FileWriteMode.APPEND);
    charSink.writeFrom(initialReader);
    initialReader.close();
}
 
源代码19 项目: tutorials   文件: AppendToFileManualTest.java
@Test
public void whenAppendToFileUsingGuava_thenCorrect() throws IOException {
    File file = new File(fileName);
    CharSink chs = com.google.common.io.Files.asCharSink(file, Charsets.UTF_8, FileWriteMode.APPEND);
    chs.write("Spain\r\n");

    assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
}
 
源代码20 项目: immutables   文件: Output.java
private void writeLinesFrom(Iterable<String> services) throws IOException {
  new CharSink() {
    @Override
    public Writer openStream() throws IOException {
      return getFiler()
          .createResource(StandardLocation.CLASS_OUTPUT, key.packageName, key.relativeName)
          .openWriter();
    }
  }.writeLines(services, "\n");
}
 
源代码21 项目: codehelper.generator   文件: IOUtils.java
public static  void writeLines(String fileName,List<String> list,Charset charset) throws IOException {
    CharSink cs = Files.asCharSink(new File(fileName), charset);
    list = PojoUtil.avoidEmptyList(list);
    cs.writeLines(list);
}
 
源代码22 项目: codehelper.generator   文件: IOUtils.java
public static  void writeLines(File file,List<String> list,Charset charset) throws IOException {
    CharSink cs = Files.asCharSink(file, charset);
    list = PojoUtil.avoidEmptyList(list);
    cs.writeLines(list);
}
 
@Override
public Writer openWriter() throws IOException {
  final StringBuilder stringBuilder = new StringBuilder(DEFAULT_FILE_SIZE);
  return new Writer() {
    @Override
    public void write(char[] chars, int start, int end) throws IOException {
      stringBuilder.append(chars, start, end - start);
    }

    @Override
    public void write(String string) throws IOException {
      stringBuilder.append(string);
    }

    @Override
    public void flush() throws IOException {}

    @Override
    public void close() throws IOException {
      try {
        formatter.formatSource(
            CharSource.wrap(stringBuilder),
            new CharSink() {
              @Override
              public Writer openStream() throws IOException {
                return fileObject.openWriter();
              }
            });
      } catch (FormatterException e) {
        // An exception will happen when the code being formatted has an error. It's better to
        // log the exception and emit unformatted code so the developer can view the code which
        // caused a problem.
        try (Writer writer = fileObject.openWriter()) {
          writer.append(stringBuilder.toString());
        }
        if (messager != null) {
          messager.printMessage(Diagnostic.Kind.NOTE, "Error formatting " + getName());
        }
      }
    }
  };
}
 
源代码24 项目: tac-kbp-eal   文件: CorpusQueryWriter.java
void writeQueries(CorpusQuerySet2016 queries, CharSink sink)
throws IOException;
 
源代码25 项目: tac-kbp-eal   文件: CorpusEventFrameWriter.java
void writeCorpusEventFrames(CorpusEventLinking corpusEventFrames, CharSink sink)
throws IOException;
 
源代码26 项目: fmt-maven-plugin   文件: FMT.java
/**
 * Hook called when the processd file is not compliant with the formatter.
 *
 * @param file the file that is not compliant
 * @param formatted the corresponding formatted of the file.
 */
@Override
protected void onNonComplyingFile(File file, String formatted) throws IOException {
  CharSink sink = Files.asCharSink(file, Charsets.UTF_8);
  sink.write(formatted);
}
 
源代码27 项目: tac-kbp-eal   文件: LinkingFileWriter.java
void write(ResponseLinking linking, CharSink sink) throws IOException; 
源代码28 项目: tac-kbp-eal   文件: KnowledgeBaseWriter.java
void write(final KnowledgeBase kb, final Random random, final CharSink sink) throws IOException;