Java 类java.io.Writer 实例源码

项目:PDF2RDF    文件:TitleExtractor.java   
private boolean process() throws IOException {
    boolean toReturn = false;
    PDFTextStripper stripper = new TitleExtractor();
    PDDocument document = null;

    try {
        document = PDDocument.load(new File(this.getFileNamePathWithExtension()));

        //((TitleExtractor) stripper).setFileNamePathWithExtension(this.getFileNamePathWithExtension());
        stripper.setSortByPosition(true);
        stripper.setStartPage(0);
        stripper.setEndPage(1);

        Writer dummy = new OutputStreamWriter(new ByteArrayOutputStream());
        stripper.writeText(document, dummy);

        setTitle(((TitleExtractor) stripper).getTitle());

        toReturn = true;
    } finally {
        if (document != null) {
            document.close();
        }
    }
    return toReturn;
}
项目:OpenJSharp    文件:JNIWriter.java   
/** Emit a class file for a given class.
 *  @param c      The class from which a class file is generated.
 */
public FileObject write(ClassSymbol c)
    throws IOException
{
    String className = c.flatName().toString();
    FileObject outFile
        = fileManager.getFileForOutput(StandardLocation.NATIVE_HEADER_OUTPUT,
            "", className.replaceAll("[.$]", "_") + ".h", null);
    Writer out = outFile.openWriter();
    try {
        write(out, c);
        if (verbose)
            log.printVerbose("wrote.file", outFile);
        out.close();
        out = null;
    } finally {
        if (out != null) {
            // if we are propogating an exception, delete the file
            out.close();
            outFile.delete();
            outFile = null;
        }
    }
    return outFile; // may be null if write failed
}
项目:OperatieBRP    文件:AttributeChild.java   
/**
 * Schrijf dit attribuut.
 *
 * @param value waarde
 * @param writer writer om XML mee te schrijven
 * @throws EncodeException bij encodeer foute
 */
@Override
public void encode(final Context context, final T value, final Writer writer) throws EncodeException {
    LOGGER.debug("encode(value={})", value);
    if (value == null) {
        return;
    }

    try {
        writer.append(" ");
        writer.append(getName());
        writer.append("=\"");
        writer.append(converter.encode(context, value));
        writer.append("\"");
    } catch (final IOException e) {
        throw new EncodeException(context.getElementStack(), e);
    }
}
项目:Backmemed    文件:UserList.java   
public void writeChanges() throws IOException
{
    Collection<V> collection = this.values.values();
    String s = this.gson.toJson((Object)collection);
    BufferedWriter bufferedwriter = null;

    try
    {
        bufferedwriter = Files.newWriter(this.saveFile, Charsets.UTF_8);
        bufferedwriter.write(s);
    }
    finally
    {
        IOUtils.closeQuietly((Writer)bufferedwriter);
    }
}
项目:openjdk-jdk10    文件:XMLKit.java   
public static void writeCData(String val, Writer w) throws IOException {
    String begCData = "<![CDATA[";
    String endCData = "]]>";
    w.write(begCData);
    for (int vpos = 0, split;; vpos = split) {
        split = val.indexOf(endCData, vpos);
        if (split < 0) {
            w.write(val, vpos, val.length() - vpos);
            w.write(endCData);
            return;
        }
        split += 2; // bisect the "]]>" goo
        w.write(val, vpos, split - vpos);
        w.write(endCData);
        w.write(begCData);
    }
}
项目:tbschedule-wed    文件:ScheduleStrategyDataManager4ZK.java   
/**
 * 导入配置信息【目前支持baseTaskType和strategy数据】
 * 
 * @param config
 * @param writer
 * @param isUpdate
 * @throws Exception
 */
public void importConfig(String config, Writer writer, boolean isUpdate)
        throws Exception {
    ConfigNode configNode = gson.fromJson(config, ConfigNode.class);
    if (configNode != null) {
        String path = configNode.getRootPath() + "/"
                + configNode.getConfigType();
        ZKTools.createPath(getZooKeeper(), path, CreateMode.PERSISTENT, zkManager.getAcl());
        String y_node = path + "/" + configNode.getName();
        if (getZooKeeper().exists(y_node, false) == null) {
            writer.append("<font color=\"red\">成功导入新配置信息\n</font>");
            getZooKeeper().create(y_node, configNode.getValue().getBytes(),
                    zkManager.getAcl(), CreateMode.PERSISTENT);
        } else if (isUpdate) {
            writer.append("<font color=\"red\">该配置信息已经存在,并且强制更新了\n</font>");
            getZooKeeper().setData(y_node,
                    configNode.getValue().getBytes(), -1);
        } else {
            writer.append("<font color=\"red\">该配置信息已经存在,如果需要更新,请配置强制更新\n</font>");
        }
    }
    writer.append(configNode.toString());
}
项目:de.flapdoodle.solid    文件:CoreFiltersTest.java   
@Test
public void testDate() throws ParseException, PebbleException, IOException {
    PebbleEngine pebble = new PebbleEngine.Builder().loader(new StringLoader()).strictVariables(false)
            .defaultLocale(Locale.ENGLISH).build();

    String source = "{{ realDate | date('MM/dd/yyyy') }}{{ realDate | date(format) }}{{ stringDate | date('yyyy/MMMM/d','yyyy-MMMM-d') }}";

    PebbleTemplate template = pebble.getTemplate(source);
    Map<String, Object> context = new HashMap<>();
    DateFormat format = new SimpleDateFormat("yyyy-MMMM-d", Locale.ENGLISH);
    Date realDate = format.parse("2012-July-01");
    context.put("realDate", realDate);
    context.put("stringDate", format.format(realDate));
    context.put("format", "yyyy-MMMM-d");

    Writer writer = new StringWriter();
    template.evaluate(writer, context);
    assertEquals("07/01/20122012-July-12012/July/1", writer.toString());
}
项目:de.flapdoodle.solid    文件:LogicTest.java   
/**
 * Tests if the macro output SafeString concatenation is working.
 */
@Test
public void testMacroSafeStringConcatenation() throws PebbleException, IOException {

    PebbleEngine pebble = new PebbleEngine.Builder().loader(new StringLoader()).strictVariables(false).build();

    String source = "{% macro macro1() %}Bob{% endmacro %}\n"
                  + "{% macro macro2() %}Maria{% endmacro %}\n"
                  + "{% macro macro3() %}John{% endmacro %}\n"
                  + "{{ (macro1() + macro2() + macro3()) | lower }}";
    PebbleTemplate template = pebble.getTemplate(source);

    Map<String, Object> context = new HashMap<>();

    Writer writer = new StringWriter();
    template.evaluate(writer, context);
    assertEquals("bobmariajohn", writer.toString());

}
项目:alfresco-repository    文件:XMLTransferManifestWriter.java   
/**
 * Start the transfer manifest
 */
public void startTransferManifest(Writer writer) throws SAXException
{
    format = OutputFormat.createPrettyPrint();
    format.setNewLineAfterDeclaration(false);
    format.setIndentSize(3);
    format.setEncoding("UTF-8");

    this.writer = new XMLWriter(writer, format);
    this.writer.startDocument();

    this.writer.startPrefixMapping(PREFIX, TransferModel.TRANSFER_MODEL_1_0_URI);
    this.writer.startPrefixMapping("cm", NamespaceService.CONTENT_MODEL_1_0_URI);

    // Start Transfer Manifest // uri, name, prefix
    this.writer.startElement(TransferModel.TRANSFER_MODEL_1_0_URI,
                ManifestModel.LOCALNAME_TRANSFER_MAINIFEST, PREFIX + ":"
                            + ManifestModel.LOCALNAME_TRANSFER_MAINIFEST, EMPTY_ATTRIBUTES);
}
项目:andbg    文件:DexAnnotator.java   
public void writeAnnotations(Writer out) throws IOException {
    List<MapItem> mapItems = dexFile.getMapItems();
    // sort the map items based on the order defined by sectionAnnotationOrder
    Ordering<MapItem> ordering = Ordering.from(new Comparator<MapItem>() {
        @Override public int compare(MapItem o1, MapItem o2) {
            return Ints.compare(sectionAnnotationOrder.get(o1.getType()), sectionAnnotationOrder.get(o2.getType()));
        }
    });

    mapItems = ordering.immutableSortedCopy(mapItems);

    try {
        for (MapItem mapItem: mapItems) {
            SectionAnnotator annotator = annotators.get(mapItem.getType());
            annotator.annotateSection(this);
        }
    } finally {
        dexFile.writeAnnotations(out, this);
    }
}
项目:elasticsearch_my    文件:CustomMustacheFactory.java   
@Override
public Writer run(Writer writer, List<Object> scopes) {
    if (getCodes() != null) {
        for (Code code : getCodes()) {
            try (StringWriter capture = new StringWriter()) {
                code.execute(capture, scopes);

                String s = capture.toString();
                if (s != null) {
                    encoder.encode(s, writer);
                }
            } catch (IOException e) {
                throw new MustacheException("Exception while parsing mustache function at line " + tc.line(), e);
            }
        }
    }
    return writer;
}
项目:s-store    文件:VoltTableUtil.java   
/**
 * Dump out a VoltTable as a CSV to the given writer
 * If the header flag is set to true, then the output will include 
 * the column names in the first row
 * @param out
 * @param vt
 * @param write_header
 */
public static void csv(Writer out, VoltTable vt, boolean header) {
    CSVWriter writer = new CSVWriter(out);

    if (header) {
        String cols[] = new String[vt.getColumnCount()];
        for (int i = 0; i < cols.length; i++) {
            cols[i] = vt.getColumnName(i);
        } // FOR
        writer.writeNext(cols);
    }
    vt.resetRowPosition();
    while (vt.advanceRow()) {
        String row[] = vt.getRowStringArray();
        assert(row != null);
        assert(row.length == vt.getColumnCount());
        writer.writeNext(row);
    } // WHILE
}
项目:incubator-netbeans    文件:CompilationUnitTest.java   
private void setupJavaTemplates() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile,
        "package zoo;\n" +
        "\n" +
        "public class A {\n" +
        "}\n"
    );

    FileObject emptyJava = FileUtil.createData(FileUtil.getConfigRoot(), "Templates/Classes/Empty.java");
    emptyJava.setAttribute("template", Boolean.TRUE);
    classJava = FileUtil.createData(FileUtil.getConfigRoot(), "Templates/Classes/Class.java");
    classJava.setAttribute("template", Boolean.TRUE);
    classJava.setAttribute("verbatim-create-from-template", Boolean.TRUE);
    template = "/*\r\ninitial\r\ncomment\r\n*/\r\npackage zoo;\r\npublic class Template {\r\n    public Template() {}\r\n}\r\n";
    Writer w = new OutputStreamWriter(classJava.getOutputStream(), "UTF-8");
    w.write(template);
    w.close();
}
项目:continuous-performance-evaluation    文件:RealtimeCargoTrackingService.java   
public void onCargoInspected(@Observes @CargoInspected Cargo cargo) {
    Writer writer = new StringWriter();

    try (JsonGenerator generator = Json.createGenerator(writer)) {
        generator
                .writeStartObject()
                .write("trackingId", cargo.getTrackingId().getIdString())
                .write("origin", cargo.getOrigin().getName())
                .write("destination", cargo.getRouteSpecification().getDestination().getName())
                .write("lastKnownLocation", cargo.getDelivery().getLastKnownLocation().getName())
                .write("transportStatus", cargo.getDelivery().getTransportStatus().toString())
                .writeEnd();
    }

    String jsonValue = writer.toString();

    for (Session session : sessions) {
        try {
            session.getBasicRemote().sendText(jsonValue);
        } catch (IOException ex) {
            logger.log(Level.WARNING, "Unable to publish WebSocket message", ex);
        }
    }

}
项目:incubator-netbeans    文件:SerialDataConvertor.java   
/** store the setting object even if was not changed */
private void writeDown() throws IOException {
    Object inst = instance.get();
    if (inst == null) return ;

    ByteArrayOutputStream b = new ByteArrayOutputStream(1024);
    Writer w = new OutputStreamWriter(b, "UTF-8"); // NOI18N
    try {
        isWriting = true;
        Convertor conv = getConvertor();
        if (conv != null) {
            conv.write(w, inst);
        } else {
            write(w, inst);
        }
    } finally {
        w.close();
        isWriting = false;
    }
    isChanged = false;

    buf = b;
    file.getFileSystem().runAtomicAction(this);
    buf = null;
    if (!isChanged) firePropertyChange(PROP_SAVE);
}
项目:incubator-netbeans    文件:XMLStorage.java   
static void save (final FileObject fo, final String content) {
    requestProcessor.post (new Runnable () {
        public void run () {
            try {
                FileLock lock = fo.lock ();
                try {
                    OutputStream os = fo.getOutputStream (lock);
                    Writer writer = new OutputStreamWriter (os, "UTF-8"); // NOI18N
                    try {
                        writer.write (content);
                    } finally {
                        writer.close ();
                    } 
                } finally {
                    lock.releaseLock ();
                }
            } catch (IOException ex) {
                ErrorManager.getDefault ().notify (ex);
            }
        }
    });
}
项目:incubator-netbeans    文件:FileBackedClobTest.java   
@Test
public void testSetCharacterStream() throws Exception {
    FileBackedClob b;
    char[] test1 = "test".toCharArray();
    char[] test2 = "test0123456789".toCharArray();
    char[] firstPartReference = new char[testCase2.length - test1.length - 4];
    char[] secondPartReference = new char[4];
    System.arraycopy(testCase2, 0, firstPartReference, 0, testCase2.length - test1.length - 4);
    System.arraycopy(testCase2, testCase2.length - 4 - 1, secondPartReference, 0, 4);
    b = new FileBackedClob(new CharArrayReader(testCase2));
    Writer os = b.setCharacterStream(testCase2.length - test1.length - 4 + 1);
    os.write(test1);
    os.close();
    assertEquals(new String(firstPartReference), b.getSubString(1, testCase2.length - test1.length - 4));
    assertEquals(new String(secondPartReference), b.getSubString(testCase2.length - 4, 4));
    assertEquals(new String(test1), b.getSubString(testCase2.length - 4 - test1.length + 1, test1.length));
    assertEquals(b.length(), 1024);
    os = b.setCharacterStream(testCase2.length - test1.length - 4 + 1);
    os.write(test2);
    os.close();
    assertEquals(new String(firstPartReference), b.getSubString(1, testCase2.length - test1.length - 4));
    assertEquals(b.length(), 1024 - test1.length - 4 + test2.length);
    assertEquals(new String(test2), b.getSubString(b.length() - test2.length + 1, test2.length));
    b.free();
}
项目:n4js    文件:AbstractTranspiler.java   
/**
 * Transpile the given resource to the given writers.
 *
 * @param resource
 *            the resource to transpile.
 * @param options
 *            the {@link GeneratorOption generator options} to use during generation.
 * @param outCode
 *            the writer where the generated output code should be sent.
 * @param optSourceMapInfo
 *            meta-info including the writer to create source-maps. If absent do not create source-maps.
 */
public void transpile(N4JSResource resource, GeneratorOption[] options, Writer outCode,
        Optional<SourceMapInfo> optSourceMapInfo) {

    // step 1: create initial transpiler state (i.e. create intermediate model, etc.)
    final TranspilerState state = prepare(resource, options);

    // step 2: execute all transformations on the transpiler state
    transform(state);

    // step 3: pretty-print the intermediate model + emit source maps (optional)
    final Optional<String> optPreamble = getPreamble();
    prettyPrint(state, outCode, optPreamble, optSourceMapInfo);
}
项目:de.flapdoodle.solid    文件:LogicTest.java   
@Test
public void testBinaryOperators() throws PebbleException, IOException {
    PebbleEngine pebble = new PebbleEngine.Builder().loader(new StringLoader()).strictVariables(false).build();

    String source = "{{ 8 + 5 * 4 - (6 + 10 / 2)  + 44 }}-{{ 10%3 }}";
    PebbleTemplate template = pebble.getTemplate(source);

    Writer writer = new StringWriter();
    template.evaluate(writer);
    assertEquals("61-1", writer.toString());
}
项目:trellis    文件:HtmlSerializer.java   
/**
 * Send the content to an output stream.
 *
 * @param out the output stream
 * @param triples the triples
 * @param subject the subject
 */
public void write(final OutputStream out, final Stream<? extends Triple> triples, final IRI subject) {
    final Writer writer = new OutputStreamWriter(out, UTF_8);
    try {
        template
            .execute(writer, new HtmlData(namespaceService, subject, triples.collect(toList()), properties))
            .flush();
    } catch (final IOException ex) {
        throw new UncheckedIOException(ex);
    }
}
项目:de.flapdoodle.solid    文件:ParsingOdditiesTest.java   
@Test
public void testExpressionInArguments() throws PebbleException, IOException {
    PebbleEngine pebble = new PebbleEngine.Builder().loader(new StringLoader()).strictVariables(false).build();

    PebbleTemplate template = pebble
            .getTemplate("{{ input(1 + 1) }}{% macro input(value) %}{{value}}{% endmacro %}");

    Writer writer = new StringWriter();
    template.evaluate(writer);
    assertEquals("2", writer.toString());
}
项目:de.flapdoodle.solid    文件:RawFilterTest.java   
@Test
public void testRawFilterWithJsonObject() throws PebbleException, IOException {
    PebbleEngine pebble = new PebbleEngine.Builder().loader(new StringLoader()).strictVariables(false).build();
    PebbleTemplate template = pebble.getTemplate("{{ text | raw }}");
    Map<String, Object> context = new HashMap<>();
    context.put("text", new JsonObject());
    Writer writer = new StringWriter();
    template.evaluate(writer, context);
    assertEquals(JsonObject.JSON_VALUE, writer.toString());
}
项目:stroom-stats    文件:XMLUtil.java   
public static String prettyPrintXML(final String xml) {
    final Reader reader = new StringReader(xml);
    final Writer writer = new StringWriter(1000);

    prettyPrintXML(reader, writer);

    return writer.toString();
}
项目:OpenJSharp    文件:SimpleDocFileFactory.java   
/**
 * Open an writer for the file, using the encoding (if any) given in the
 * doclet configuration.
 * The file must have been created with a location of
 * {@link DocumentationTool.Location#DOCUMENTATION_OUTPUT} and a corresponding relative path.
 */
public Writer openWriter() throws IOException, UnsupportedEncodingException {
    if (location != DocumentationTool.Location.DOCUMENTATION_OUTPUT)
        throw new IllegalStateException();

    createDirectoryForFile(file);
    FileOutputStream fos = new FileOutputStream(file);
    if (configuration.docencoding == null) {
        return new BufferedWriter(new OutputStreamWriter(fos));
    } else {
        return new BufferedWriter(new OutputStreamWriter(fos, configuration.docencoding));
    }
}
项目:lams    文件:Dom4JDriver.java   
@Override
public HierarchicalStreamWriter createWriter(final Writer out) {
    final HierarchicalStreamWriter[] writer = new HierarchicalStreamWriter[1];
    final FilterWriter filter = new FilterWriter(out) {
        @Override
        public void close() {
            writer[0].close();
        }
    };
    writer[0] = new Dom4JXmlWriter(new XMLWriter(filter, outputFormat), getNameCoder());
    return writer[0];
}
项目:powsybl-core    文件:AbstractValidationFormatterWriterTest.java   
protected void testFlows(String flowsContent, boolean verbose) throws IOException {
    Writer writer = new StringWriter();
    TableFormatterConfig config = new TableFormatterConfig(Locale.getDefault(), ';', "inv", true, true);
    try (ValidationWriter flowsWriter = getFlowsValidationFormatterCsvWriter(config, writer, verbose)) {
        flowsWriter.write(branchId, p1, p1Calc, q1, q1Calc, p2, p2Calc, q2, q2Calc, r, x, g1, g2, b1, b2, rho1, rho2,
                          alpha1, alpha2, u1, u2, theta1, theta2, z, y, ksi, connected1, connected2, mainComponent1,
                          mainComponent2, validated);
        assertEquals(flowsContent, writer.toString().trim());
    }
}
项目:HuskyCrates-Sponge    文件:JSONWriter.java   
/**
 * Make a fresh JSONWriter. It can be used to build one JSON text.
 */
public JSONWriter(Writer w) {
    this.comma = false;
    this.mode = 'i';
    this.stack = new JSONObject[maxdepth];
    this.top = 0;
    this.writer = w;
}
项目:qpp-conversion-tool    文件:ConversionFileWriterWrapper.java   
/**
 * Write out the QPP to a file.
 *
 * @param jsonWrapper The QPP to write
 * @param outFile The location to write.
 */
private void writeOutQpp(JsonWrapper jsonWrapper, Path outFile) {
    try (Writer writer = Files.newBufferedWriter(outFile)) {
        writer.write(jsonWrapper.toString());
        writer.flush();
    } catch (IOException exception) {
        DEV_LOG.error("Could not write out QPP JSON to file", exception);
    }
}
项目:OpenDA    文件:NetcdfUtils.java   
/**
 * Converts the data in the given netcdf file to text format and returns this as a String.
 * This can be used e.g. in unit tests to compare the data in human readable text format instead of in binary format.
 *
 * @param netcdfFile netcdf file
 * @param variableNames semicolon delimited list of variables of which the data should be printed.
 *                      If this is null or empty, then all variables are printed.
 * @return String with cdl representation of the data.
 * @throws IOException
 */
public static String netcdfFileToString(File netcdfFile, String variableNames) throws IOException {
    boolean printAllVariables = false;
    if (variableNames == null || variableNames.isEmpty()) {
        printAllVariables = true;
        variableNames = null;
    }

    Writer writer = new StringWriter();
    NCdumpW.print(netcdfFile.getAbsolutePath(), writer, printAllVariables, false, false, true, variableNames, null);
    return writer.toString();
}
项目:de.flapdoodle.solid    文件:InheritanceTest.java   
@Test
public void testMultiLevelInheritance() throws PebbleException, IOException {
    PebbleEngine pebble = new PebbleEngine.Builder().strictVariables(false).build();
    PebbleTemplate template = pebble.getTemplate("templates/template.child.peb");

    Writer writer = new StringWriter();
    template.evaluate(writer);
    assertEquals("GRANDFATHER TEXT ABOVE HEAD" + LINE_SEPARATOR + LINE_SEPARATOR + "\tCHILD HEAD" + LINE_SEPARATOR
            + LINE_SEPARATOR + "GRANDFATHER TEXT BELOW HEAD AND ABOVE FOOT" + LINE_SEPARATOR + LINE_SEPARATOR + "\tGRANDFATHER FOOT" + LINE_SEPARATOR + LINE_SEPARATOR
            + "GRANDFATHER TEXT BELOW FOOT", writer.toString());
}
项目:OpenJSharp    文件:ToStream.java   
/**
 * Handle one of the default entities, return false if it
 * is not a default entity.
 *
 * @param ch character to be escaped.
 * @param i index into character array.
 * @param chars non-null reference to character array.
 * @param len length of chars.
 * @param fromTextNode true if the characters being processed
 * are from a text node, false if they are from an attribute value
 * @param escLF true if the linefeed should be escaped.
 *
 * @return i+1 if the character was written, else i.
 *
 * @throws java.io.IOException
 */
protected int accumDefaultEntity(
    java.io.Writer writer,
    char ch,
    int i,
    char[] chars,
    int len,
    boolean fromTextNode,
    boolean escLF)
    throws IOException
{

    if (!escLF && CharInfo.S_LINEFEED == ch)
    {
        writer.write(m_lineSep, 0, m_lineSepLen);
    }
    else
    {
        // if this is text node character and a special one of those,
        // or if this is a character from attribute value and a special one of those
        if ((fromTextNode && m_charInfo.isSpecialTextChar(ch)) || (!fromTextNode && m_charInfo.isSpecialAttrChar(ch)))
        {
            String outputStringForChar = m_charInfo.getOutputStringForChar(ch);

            if (null != outputStringForChar)
            {
                writer.write(outputStringForChar);
            }
            else
                return i;
        }
        else
            return i;
    }

    return i + 1;

}
项目:guava-mock    文件:CharStreamsTest.java   
public void testNullWriter() throws Exception {
  // create a null writer
  Writer nullWriter = CharStreams.nullWriter();
  // write to the writer
  nullWriter.write('n');
  String test = "Test string for NullWriter";
  nullWriter.write(test);
  nullWriter.write(test, 2, 10);
  // nothing really to assert?
  assertSame(CharStreams.nullWriter(), CharStreams.nullWriter());
}
项目:mustache-showcase    文件:NavActiveLambda.java   
@Override
public void execute(Template.Fragment frag, Writer out) throws IOException {
    String body = frag.execute();
    if (body.equals(((Map) frag.context()).get(NavNameLambda.NAME))) {
        out.write(ACTIVE_CLASS_NAME);
    }
}
项目:googles-monorepo-demo    文件:CharStreamsTest.java   
public void testAsWriter() {
  // Should wrap Appendable in a new object
  Appendable plainAppendable = new StringBuilder();
  Writer result = CharStreams.asWriter(plainAppendable);
  assertNotSame(plainAppendable, result);
  assertNotNull(result);

  // A Writer should not be wrapped
  Appendable secretlyAWriter = new StringWriter();
  result = CharStreams.asWriter(secretlyAWriter);
  assertSame(secretlyAWriter, result);
}
项目:otus_java_2017_06    文件:TemplateProcessor.java   
String getPage(String filename, Map<String, Object> data) throws IOException {
    try (Writer stream = new StringWriter();) {
        Template template = configuration.getTemplate(filename);
        template.process(data, stream);
        return stream.toString();
    } catch (TemplateException e) {
        throw new IOException(e);
    }
}
项目:openjdk-jdk10    文件:ElementStructureTest.java   
void realClasses(String location, Predicate<String> acceptor, Writer output, String version) throws Exception {
    Path classes = Paths.get(location);
    Map<String, JavaFileObject> className2File = new HashMap<>();
    Map<JavaFileObject, String> file2ClassName = new HashMap<>();

    try (BufferedReader descIn = Files.newBufferedReader(classes)) {
        String classFileData;

        while ((classFileData = descIn.readLine()) != null) {
            ByteArrayOutputStream data = new ByteArrayOutputStream();
            for (int i = 0; i < classFileData.length(); i += 2) {
                data.write(Integer.parseInt(classFileData.substring(i, i + 2), 16));
            }
            JavaFileObject file = new ByteArrayJavaFileObject(data.toByteArray());
            try (InputStream in = new ByteArrayInputStream(data.toByteArray())) {
                String name = ClassFile.read(in).getName().replace("/", ".");
                className2File.put(name, file);
                file2ClassName.put(file, name);
            } catch (IOException | ConstantPoolException ex) {
                throw new IllegalStateException(ex);
            }
        }
    }

    try (JavaFileManager fm = new TestFileManager(className2File, file2ClassName)) {
        JavacTaskImpl task = (JavacTaskImpl) ToolProvider.getSystemJavaCompiler().getTask(null, fm, null, Arrays.asList("-source", version), null, Arrays.asList(new ToolBox.JavaSource("Test", "")));
        task.parse();

        PACK: for (String pack : packages(fm)) {
            PackageElement packEl = task.getElements().getPackageElement(pack);
            assert packEl != null;
            new ExhaustiveElementScanner(task, output, acceptor).visit(packEl);
        }
    }
}
项目:GitHub    文件: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");
}
项目:tac-kbp-eal    文件:GoldArgumentCountsInspector.java   
static void writeTsv(ImmutableMultiset<String> data, File file) throws IOException {
  try (Writer out = Files.asCharSink(file, Charsets.UTF_8).openBufferedStream()) {
    for (Entry<String> e : Multisets.copyHighestCountFirst(data).entrySet()) {
      out.write(e.getElement() + "\t" + e.getCount() + "\n");
    }
  }
}
项目:hadoop    文件:TestEncryptedShuffle.java   
private void encryptedShuffleWithCerts(boolean useClientCerts)
  throws Exception {
  try {
    Configuration conf = new Configuration();
    String keystoresDir = new File(BASEDIR).getAbsolutePath();
    String sslConfsDir =
      KeyStoreTestUtil.getClasspathDir(TestEncryptedShuffle.class);
    KeyStoreTestUtil.setupSSLConfig(keystoresDir, sslConfsDir, conf,
                                    useClientCerts);
    conf.setBoolean(MRConfig.SHUFFLE_SSL_ENABLED_KEY, true);
    startCluster(conf);
    FileSystem fs = FileSystem.get(getJobConf());
    Path inputDir = new Path("input");
    fs.mkdirs(inputDir);
    Writer writer =
      new OutputStreamWriter(fs.create(new Path(inputDir, "data.txt")));
    writer.write("hello");
    writer.close();

    Path outputDir = new Path("output", "output");

    JobConf jobConf = new JobConf(getJobConf());
    jobConf.setInt("mapred.map.tasks", 1);
    jobConf.setInt("mapred.map.max.attempts", 1);
    jobConf.setInt("mapred.reduce.max.attempts", 1);
    jobConf.set("mapred.input.dir", inputDir.toString());
    jobConf.set("mapred.output.dir", outputDir.toString());
    JobClient jobClient = new JobClient(jobConf);
    RunningJob runJob = jobClient.submitJob(jobConf);
    runJob.waitForCompletion();
    Assert.assertTrue(runJob.isComplete());
    Assert.assertTrue(runJob.isSuccessful());
  } finally {
    stopCluster();
  }
}
项目:openjdk-jdk10    文件:EncodingInfo.java   
/**
 * Returns a writer for this encoding based on
 * an output stream.
 *
 * @return A suitable writer
 * @exception UnsupportedEncodingException There is no convertor
 *  to support this encoding
 */
public Writer getWriter(OutputStream output)
    throws UnsupportedEncodingException {
    // this should always be true!
    if (javaName != null)
        return new OutputStreamWriter(output, javaName);
    javaName = EncodingMap.getIANA2JavaMapping(ianaName);
    if(javaName == null)
        // use UTF-8 as preferred encoding
        return new OutputStreamWriter(output, "UTF8");
    return new OutputStreamWriter(output, javaName);
}