Java Code Examples for com.google.common.io.CharSink

The following examples show how to use com.google.common.io.CharSink. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: google-ads-java   Source File: MethodsListGenerator.java    License: Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 2
Source Project: tac-kbp-eal   Source File: DefaultCorpusQueryWriter.java    License: MIT License 6 votes vote down vote up
@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());
}
 
Example 3
Source Project: tac-kbp-eal   Source File: CorpusEventFrameWriter2016.java    License: MIT License 6 votes vote down vote up
@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");
    }
  }
}
 
Example 4
Source Project: tutorials   Source File: JavaXToWriterUnitTest.java    License: MIT License 6 votes vote down vote up
@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());
}
 
Example 5
Source Project: java-n-IDE-for-Android   Source File: Formatter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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()));
}
 
Example 6
@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());
        }
      }
    }
  };
}
 
Example 7
Source Project: qmq   Source File: BatchFileAppender.java    License: Apache License 2.0 5 votes vote down vote up
private void writeBatch(final CharSink sink, final List<String> batch) {
    try {
        sink.writeLines(batch);
    } catch (IOException e) {
        LOG.error("write lines failed.", e);
    }
}
 
Example 8
Source Project: javaide   Source File: Formatter.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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()));
}
 
Example 9
@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());
        }
      }
    }
  };
}
 
Example 10
Source Project: j2cl   Source File: BazelJ2clRta.java    License: Apache License 2.0 5 votes vote down vote up
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);
  }
}
 
Example 11
Source Project: google-java-format   Source File: Formatter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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()));
}
 
Example 12
Source Project: tac-kbp-eal   Source File: SingleFileQueryStoreWriter.java    License: MIT License 5 votes vote down vote up
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();
}
 
Example 13
Source Project: tac-kbp-eal   Source File: AbstractKBPSpecLinkingWriter.java    License: MIT License 5 votes vote down vote up
@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");
}
 
Example 14
Source Project: tac-kbp-eal   Source File: KBPAssessmentDiff.java    License: MIT License 5 votes vote down vote up
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);
}
 
Example 15
Source Project: ipmi4j   Source File: IpmiCommandNameTest.java    License: Apache License 2.0 5 votes vote down vote up
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);
        }
    }
}
 
Example 16
Source Project: tutorials   Source File: GuavaIOUnitTest.java    License: MIT License 5 votes vote down vote up
@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);
}
 
Example 17
Source Project: tutorials   Source File: GuavaIOUnitTest.java    License: MIT License 5 votes vote down vote up
@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());

}
 
Example 18
Source Project: tutorials   Source File: JavaReaderToXUnitTest.java    License: MIT License 5 votes vote down vote up
@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();
}
 
Example 19
Source Project: tutorials   Source File: AppendToFileManualTest.java    License: MIT License 5 votes vote down vote up
@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");
}
 
Example 20
Source Project: immutables   Source File: Output.java    License: Apache License 2.0 5 votes vote down vote up
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");
}
 
Example 21
Source Project: codehelper.generator   Source File: IOUtils.java    License: Apache License 2.0 4 votes vote down vote up
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);
}
 
Example 22
Source Project: codehelper.generator   Source File: IOUtils.java    License: Apache License 2.0 4 votes vote down vote up
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);
}
 
Example 23
@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());
        }
      }
    }
  };
}
 
Example 24
Source Project: tac-kbp-eal   Source File: CorpusQueryWriter.java    License: MIT License 4 votes vote down vote up
void writeQueries(CorpusQuerySet2016 queries, CharSink sink)
throws IOException;
 
Example 25
Source Project: tac-kbp-eal   Source File: CorpusEventFrameWriter.java    License: MIT License 4 votes vote down vote up
void writeCorpusEventFrames(CorpusEventLinking corpusEventFrames, CharSink sink)
throws IOException;
 
Example 26
Source Project: fmt-maven-plugin   Source File: FMT.java    License: MIT License 2 votes vote down vote up
/**
 * 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);
}
 
Example 27
Source Project: tac-kbp-eal   Source File: LinkingFileWriter.java    License: MIT License votes vote down vote up
void write(ResponseLinking linking, CharSink sink) throws IOException; 
Example 28
Source Project: tac-kbp-eal   Source File: KnowledgeBaseWriter.java    License: MIT License votes vote down vote up
void write(final KnowledgeBase kb, final Random random, final CharSink sink) throws IOException;