Example usage for java.io OutputStreamWriter OutputStreamWriter

List of usage examples for java.io OutputStreamWriter OutputStreamWriter

Introduction

In this page you can find the example usage for java.io OutputStreamWriter OutputStreamWriter.

Prototype

public OutputStreamWriter(OutputStream out, CharsetEncoder enc) 

Source Link

Document

Creates an OutputStreamWriter that uses the given charset encoder.

Usage

From source file:edu.illinois.cs.cogcomp.wikifier.wiki.importing.WikipediaRedirectExtractor.java

public String run(File inputFile, File outputFile) throws Exception {
    int invalidCount = 0;
    long t0 = System.currentTimeMillis();
    InputStream fis = new FileInputStream(inputFile);
    if (inputFile.getName().endsWith(".bz2"))
        fis = new BZip2InputStream(fis, false);

    BufferedReader dumpReader = new BufferedReader(new InputStreamReader(fis, "utf-8"));

    BufferedWriter redirectWriter = new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream(outputFile), "utf-8"));

    String titleIdFile = outputFile + "-title-id.txt";
    BufferedWriter titleIdWriter = new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream(titleIdFile), "utf-8"));

    int count = 0;
    String title = null;//from   w ww  .  j a va  2s.c o m
    String line = null;
    while ((line = dumpReader.readLine()) != null) {
        if (line.startsWith(titlePattern)) {
            title = cleanupTitle(line);
            continue;
        }
        if (line.startsWith(redirectPattern)) {
            String[] splits = StringUtils.substringsBetween(line, "<redirect title=\"", "\" />");
            if (splits == null || splits.length != 1) {
                invalidCount++;
                continue;
            }
            String redirectedTitle = splits[0];
            redirectedTitle = cleanupTitle(redirectedTitle);
            if (isValidAlias(title, redirectedTitle)) {
                redirectWriter.write(title + "\t" + redirectedTitle);
                redirectWriter.newLine();
                count++;
            } else {
                invalidCount++;
                System.out.println("Discarded redirect from " + title + " to " + redirectedTitle);
            }
            if (count % 100000 == 0)
                System.out.println("Processed " + (count + invalidCount) + " titles ");
        }

        if (SAVE_COMPLETE_TITLE_LIST && line.startsWith(idPattern)) {
            String[] splits = StringUtils.substringsBetween(line, "<id>", "</id>");
            if (splits == null || splits.length != 1) {
                invalidCount++;
                continue;
            }
            titleIdWriter.write(splits[0] + '\t' + title);
            titleIdWriter.newLine();
        }

    }

    dumpReader.close();
    fis.close();

    redirectWriter.close();
    titleIdWriter.close();

    System.out.println("---- Wikipedia redirect extraction done ----");
    long t1 = System.currentTimeMillis();
    // IOUtil.save( map );
    System.out.println("Discarded " + invalidCount + " redirects to wikipedia meta articles.");
    System.out.println("Extracted " + count + " redirects.");
    System.out.println("Saved output: " + outputFile.getAbsolutePath());
    System.out.println("Done in " + ((t1 - t0) / 1000) + " sec.");
    return titleIdFile;
}

From source file:com.personalserver.HomeCommandHandler.java

@Override
public void handle(HttpRequest httpRequest, HttpResponse httpResponse, HttpContext httpContext)
        throws HttpException, IOException {

    this.mHost = httpRequest.getFirstHeader("Host").getValue();
    System.out.println("Host : " + mHost);
    HttpEntity entity = new EntityTemplate(new ContentProducer() {
        public void writeTo(final OutputStream outstream) throws IOException {
            OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
            String html = "<html><head></head>" + "<body><center><h1>Welcome to Personal Server<h1></center>"
                    + "<p>to browse file click <a href=\"http://" + mHost + "/dir\">here</a></p>"
                    + "</body></html>";

            // html = AssetsUtils.readHtmlForName(mContext, "home");

            writer.write(html);//from  w  ww .j  a  v  a 2 s  .  c  o m
            writer.flush();
        }
    });

    httpResponse.setHeader("Content-Type", "text/html");
    httpResponse.setEntity(entity);
}

From source file:com.googlesource.gerrit.plugins.lfs.locks.LfsLocksContext.java

LfsLocksContext(LfsGson gson, final HttpServletRequest req, final HttpServletResponse res) {
    this.path = req.getPathInfo().startsWith("/") ? req.getPathInfo() : "/" + req.getPathInfo();
    this.req = req;
    this.res = res;
    this.writer = Suppliers.memoize(new Supplier<Writer>() {
        @Override/*from   ww  w .  java  2s  . co m*/
        public Writer get() {
            try {
                return new BufferedWriter(new OutputStreamWriter(res.getOutputStream(), UTF_8));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    });
    this.reader = Suppliers.memoize(new Supplier<Reader>() {
        @Override
        public Reader get() {
            try {
                return new BufferedReader(new InputStreamReader(req.getInputStream(), UTF_8));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    });
    this.gson = gson;
    setLfsResponseType();
}

From source file:gdv.xport.util.AbstractFormatterTest.java

/**
 * Tested die Formattierung der Musterdatei als HTML.
 *
 * @param formatter the formatter/* w w  w .ja va  2s .c o  m*/
 * @param filename the filename
 * @throws IOException falls was schiefgelaufen ist
 * @throws XMLStreamException falls was schiefgelaufen ist
 */
protected static void exportMusterdatei(final AbstractFormatter formatter, final String filename)
        throws IOException, XMLStreamException {
    Datenpaket datenpaket = new Datenpaket();
    InputStream istream = AbstractFormatterTest.class.getResourceAsStream("/musterdatei_041222.txt");
    File siteDir = new File("target", "site");
    if (siteDir.mkdirs()) {
        log.info("created: " + siteDir);
    }
    File exportFile = new File(siteDir, filename);
    Writer writer = new OutputStreamWriter(new FileOutputStream(exportFile), "ISO-8859-1");
    try {
        datenpaket.importFrom(istream);
        formatter.setWriter(writer);
        formatter.write(datenpaket);
        log.info(datenpaket + " exported to " + exportFile);
    } finally {
        writer.close();
        istream.close();
    }
}

From source file:de.innovationgate.utils.XStreamUtils.java

/**
 * Serializes an object to a UTF-8 encoded output stream
 * @param obj The object to write/*from www.j  av  a  2  s  . c o m*/
 * @param xstream The XStream instance to use
 * @param out The output stream to write to
 * @throws IOException
 */
public static void writeUtf8ToOutputStream(Object obj, XStream xstream, OutputStream out) throws IOException {
    BufferedOutputStream bufOut = new BufferedOutputStream(out);
    OutputStreamWriter writer;
    try {
        writer = new OutputStreamWriter(bufOut, "UTF-8");
        xstream.toXML(obj, writer);
        writer.flush();
        writer.close();
    } catch (UnsupportedEncodingException e) {
        // Cannot happen since Java always supports UTF-8
    }
}

From source file:com.zb.app.common.component.ComponentController.java

@ExceptionHandler(Throwable.class)
public ModelAndView handleIOException(Throwable e) throws Throwable {

    if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
        throw e;// w w  w  .j  av  a  2 s.c om
    }

    if (request == null && response == null) {
        throw e;
    }

    if (request == null && response != null) {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        OutputStream out = response.getOutputStream();
        PrintWriter pw = new PrintWriter(new OutputStreamWriter(out, "utf-8"));
        pw.println("{\"code\":1,\"msg\":\",?!\",\"data\":\"\"}");
        pw.flush();
        pw.close();
    }

    ModelAndView mav = new ModelAndView();
    if (InvokeTypeTools.isAjax(request)) {
        return createJsonMav("server exceptin or error", ResultCode.ERROR, e.getMessage());
    }

    mav.addObject("exception", e.getCause() == null ? StringUtils.EMPTY : e.getCause().toString());
    mav.addObject("msg", StringUtils.isEmpty(e.getMessage()) ? e.toString() : e.getMessage());
    mav.addObject("stackTrace", e.getStackTrace().toString());
    if (request.getRequestURI() != null) {
        mav.addObject("url", request.getRequestURI().toString());
    }
    mav.setViewName("error");
    return mav;
}

From source file:fr.itinerennes.bundler.tasks.framework.AbstractCountedCsvTask.java

@PostExec
public void prependLineCount() throws IOException {

    LOGGER.debug("Inserting line count at file head: {}", lineCount);

    final File output = getOutputFile();
    final File source = File.createTempFile("itr-", output.getName(), output.getParentFile());
    source.delete();/*from  w  w  w. j  a v  a2s .  com*/
    FileUtils.moveFile(output, source);

    InputStream from = null;
    BufferedWriter to = null;
    try {
        from = new FileInputStream(source);
        to = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output), CHARSET));
        to.write(String.valueOf(lineCount));
        to.newLine();
        final LineIterator i = IOUtils.lineIterator(from, CHARSET.name());
        while (i.hasNext()) {
            to.write(i.next());
            to.newLine();
        }
    } finally {
        IOUtils.closeQuietly(from);
        IOUtils.closeQuietly(to);
        FileUtils.deleteQuietly(source);
    }
}

From source file:org.exist.xquery.modules.jfreechart.render.SVGrenderer.java

@Override
public void render(JFreeChart chart, Configuration config, OutputStream os) throws IOException {

    Rectangle bounds = new Rectangle(config.getImageWidth(), config.getImageHeight());

    // Get a DOMImplementation and create an XML document
    DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
    Document document = domImpl.createDocument(null, "svg", null);

    // Create an instance of the SVG Generator
    SVGGraphics2D svgGenerator = new SVGGraphics2D(document);

    // draw the chart in the SVG generator
    chart.draw(svgGenerator, bounds);/*  w w w  .  j  a v  a2  s.c o m*/

    Writer out = new OutputStreamWriter(os, "UTF-8");
    svgGenerator.stream(out, true /* use css */);
    os.flush();
    os.close();
}

From source file:melnorme.utilbox.misc.FileUtil.java

/** Writes given chars array to given writer. 
 * Close writer afterwards. *//*w  w  w  .  ja  va 2  s  . com*/
public static void writeCharsToFile(File file, char[] chars, Charset charset)
        throws IOException, FileNotFoundException {
    FileOutputStream fileOS = new FileOutputStream(file);
    OutputStreamWriter osWriter = new OutputStreamWriter(fileOS, charset);
    StreamUtil.writeCharsToWriter(chars, osWriter);
}