com.google.common.io.CharSink Java Examples

The following examples show how to use com.google.common.io.CharSink. 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 File: MethodsListGenerator.java    From google-ads-java with 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 File: JavaXToWriterUnitTest.java    From tutorials with 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 #3
Source File: CorpusEventFrameWriter2016.java    From tac-kbp-eal with 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 File: DefaultCorpusQueryWriter.java    From tac-kbp-eal with 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 #5
Source File: FormattingJavaFileObject.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
@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 #6
Source File: Output.java    From immutables with 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 #7
Source File: AppendToFileManualTest.java    From tutorials with 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 #8
Source File: JavaReaderToXUnitTest.java    From tutorials with 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 #9
Source File: GuavaIOUnitTest.java    From tutorials with 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 #10
Source File: GuavaIOUnitTest.java    From tutorials with 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 #11
Source File: IpmiCommandNameTest.java    From ipmi4j with 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 #12
Source File: KBPAssessmentDiff.java    From tac-kbp-eal with 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 #13
Source File: AbstractKBPSpecLinkingWriter.java    From tac-kbp-eal with 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 File: SingleFileQueryStoreWriter.java    From tac-kbp-eal with 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 #15
Source File: Formatter.java    From google-java-format with 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 #16
Source File: BazelJ2clRta.java    From j2cl with 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 #17
Source File: FormattingJavaFileObject.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@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 #18
Source File: Formatter.java    From javaide with 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 #19
Source File: BatchFileAppender.java    From qmq with 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 #20
Source File: Formatter.java    From java-n-IDE-for-Android with 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 #21
Source File: CorpusEventFrameWriter.java    From tac-kbp-eal with MIT License 4 votes vote down vote up
void writeCorpusEventFrames(CorpusEventLinking corpusEventFrames, CharSink sink)
throws IOException;
 
Example #22
Source File: CorpusQueryWriter.java    From tac-kbp-eal with MIT License 4 votes vote down vote up
void writeQueries(CorpusQuerySet2016 queries, CharSink sink)
throws IOException;
 
Example #23
Source File: FormattingJavaFileObject.java    From google-java-format with Apache License 2.0 4 votes vote down vote up
@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 File: IOUtils.java    From codehelper.generator with 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 #25
Source File: IOUtils.java    From codehelper.generator with 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 #26
Source File: FMT.java    From fmt-maven-plugin with 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 File: LinkingFileWriter.java    From tac-kbp-eal with MIT License votes vote down vote up
void write(ResponseLinking linking, CharSink sink) throws IOException; 
Example #28
Source File: KnowledgeBaseWriter.java    From tac-kbp-eal with MIT License votes vote down vote up
void write(final KnowledgeBase kb, final Random random, final CharSink sink) throws IOException;