下面列出了怎么用com.google.common.io.CharSink的API类实例代码及写法,或者点击链接到github查看源代码。
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);
}
@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());
}
@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");
}
}
}
@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());
}
/**
* 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());
}
}
}
};
}
private void writeBatch(final CharSink sink, final List<String> batch) {
try {
sink.writeLines(batch);
} catch (IOException e) {
LOG.error("write lines failed.", e);
}
}
/**
* 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());
}
}
}
};
}
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);
}
}
/**
* 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()));
}
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();
}
@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");
}
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);
}
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);
}
}
}
@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);
}
@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());
}
@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();
}
@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");
}
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");
}
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);
}
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());
}
}
}
};
}
void writeQueries(CorpusQuerySet2016 queries, CharSink sink)
throws IOException;
void writeCorpusEventFrames(CorpusEventLinking corpusEventFrames, CharSink sink)
throws IOException;
/**
* 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);
}
void write(ResponseLinking linking, CharSink sink) throws IOException;
void write(final KnowledgeBase kb, final Random random, final CharSink sink) throws IOException;