Example usage for java.io Writer flush

List of usage examples for java.io Writer flush

Introduction

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

Prototype

public abstract void flush() throws IOException;

Source Link

Document

Flushes the stream.

Usage

From source file:Main.java

public static void main(String[] args) {
    int c = 70;/*from   w w w .j  av  a2 s  . co  m*/

    Writer writer = new PrintWriter(System.out);

    try {
        // write an int that will be printed as ASCII
        writer.write(c);

        // flush the writer
        writer.flush();

        // write another int that will be printed as ASCII
        writer.write(71);

        // flush the stream again
        writer.flush();

    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:Main.java

public static void main(String[] args) {
    CharSequence csq = "from java2s.com!";

    Writer writer = new PrintWriter(System.out);

    try {/*from w  w  w.  ja  v a  2s  .  c o  m*/
        // append a sequence and change line
        writer.append("This is an example\n");

        // flush the writer
        writer.flush();

        // append a new sequence
        writer.append(csq);

        // flush the writer to see the result
        writer.flush();

    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:Main.java

public static void main(String[] args) {
    char c = 'A';

    Writer writer = new PrintWriter(System.out);

    try {//  w  w  w.  jav  a 2  s .c  o m
        // append a char
        writer.append('c');

        // append a new char
        writer.append(c);

        // flush the writer to see the result
        writer.flush();

    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:Main.java

public static void main(String args[]) throws Exception {
    String[] words = { "", "e", "a", "c" };
    Writer w = new BufferedWriter(new OutputStreamWriter(System.out, "Cp850"));
    for (int i = 0; i < 4; i++) {
        w.write(words[i] + " ");
    }/* w ww  .  ja  v a  2 s. com*/
    Arrays.sort(words);
    for (int i = 0; i < 4; i++) {
        w.write(words[i] + " ");
    }
    w.flush();
    w.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    InputStream is = new FileInputStream("test.xml");
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();

    Document oldDoc = builder.parse(is);
    Node oldRoot = oldDoc.getDocumentElement();
    Document newDoc = builder.newDocument();
    Element newRoot = newDoc.createElement("newroot");
    newDoc.appendChild(newRoot);/*  www .  jav a2 s .c om*/
    newRoot.appendChild(newDoc.importNode(oldRoot, true));

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    DOMSource domSource = new DOMSource(newDoc);
    Writer writer = new OutputStreamWriter(out);
    StreamResult result = new StreamResult(writer);
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.transform(domSource, result);
    writer.flush();

    InputStream isNewXML = new ByteArrayInputStream(out.toByteArray());
}

From source file:Main.java

public static void main(String args[]) throws Exception {
    String[] words = { "", "e", "a", "c" };
    Writer w = new BufferedWriter(new OutputStreamWriter(System.out, "Cp850"));
    for (int i = 0; i < 4; i++) {
        w.write(words[i] + " ");
    }//from w  w w . j  av a  2  s .  c  om
    sortArray(Collator.getInstance(), words);
    for (int i = 0; i < 4; i++) {
        w.write(words[i] + " ");
    }
    w.flush();
    w.close();
}

From source file:com.cncounter.test.httpclient.ProxyTunnelDemo.java

public final static void main(String[] args) throws Exception {

    ProxyClient proxyClient = new ProxyClient();
    HttpHost target = new HttpHost("www.google.com", 80);
    HttpHost proxy = new HttpHost("localhost", 1080);
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user", "pwd");
    Socket socket = proxyClient.tunnel(proxy, target, credentials);
    try {/*  w  ww  .jav  a 2 s.com*/
        Writer out = new OutputStreamWriter(socket.getOutputStream(), HTTP.DEF_CONTENT_CHARSET);
        out.write("GET / HTTP/1.1\r\n");
        out.write("Host: " + target.toHostString() + "\r\n");
        out.write("Agent: whatever\r\n");
        out.write("Connection: close\r\n");
        out.write("\r\n");
        out.flush();
        BufferedReader in = new BufferedReader(
                new InputStreamReader(socket.getInputStream(), HTTP.DEF_CONTENT_CHARSET));
        String line = null;
        while ((line = in.readLine()) != null) {
            System.out.println(line);
        }
    } finally {
        socket.close();
    }
}

From source file:com.dlmu.heipacker.crawler.client.ProxyTunnelDemo.java

public final static void main(String[] args) throws Exception {

    ProxyClient proxyClient = new ProxyClient();
    HttpHost target = new HttpHost("www.yahoo.com", 80);
    HttpHost proxy = new HttpHost("localhost", 8888);
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user", "pwd");
    Socket socket = proxyClient.tunnel(proxy, target, credentials);
    try {/*from  ww w.  j  a  v a  2 s.  c  o m*/
        Writer out = new OutputStreamWriter(socket.getOutputStream(), HTTP.DEF_CONTENT_CHARSET);
        out.write("GET / HTTP/1.1\r\n");
        out.write("Host: " + target.toHostString() + "\r\n");
        out.write("Agent: whatever\r\n");
        out.write("Connection: close\r\n");
        out.write("\r\n");
        out.flush();
        BufferedReader in = new BufferedReader(
                new InputStreamReader(socket.getInputStream(), HTTP.DEF_CONTENT_CHARSET));
        String line = null;
        while ((line = in.readLine()) != null) {
            System.out.println(line);
        }
    } finally {
        socket.close();
    }
}

From source file:ProxyTunnelDemo.java

public static void main(String[] args) throws Exception {

    ProxyClient proxyclient = new ProxyClient();
    // set the host the proxy should create a connection to
    ///*w  ww .j  a va  2 s  . c  o  m*/
    // Note:  By default port 80 will be used. Some proxies only allow conections
    // to ports 443 and 8443.  This is because the HTTP CONNECT method was intented
    // to be used for tunneling HTTPS.
    proxyclient.getHostConfiguration().setHost("www.yahoo.com");
    // set the proxy host and port
    proxyclient.getHostConfiguration().setProxy("10.0.1.1", 3128);
    // set the proxy credentials, only necessary for authenticating proxies
    proxyclient.getState().setProxyCredentials(new AuthScope("10.0.1.1", 3128, null),
            new UsernamePasswordCredentials("proxy", "proxy"));

    // create the socket
    ProxyClient.ConnectResponse response = proxyclient.connect();

    if (response.getSocket() != null) {
        Socket socket = response.getSocket();
        try {
            // go ahead and do an HTTP GET using the socket
            Writer out = new OutputStreamWriter(socket.getOutputStream(), "ISO-8859-1");
            out.write("GET http://www.yahoo.com/ HTTP/1.1\r\n");
            out.write("Host: www.yahoo.com\r\n");
            out.write("Agent: whatever\r\n");
            out.write("\r\n");
            out.flush();
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(socket.getInputStream(), "ISO-8859-1"));
            String line = null;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
        } finally {
            // be sure to close the socket when we're done
            socket.close();
        }
    } else {
        // the proxy connect was not successful, check connect method for reasons why
        System.out.println("Connect failed: " + response.getConnectMethod().getStatusLine());
        System.out.println(response.getConnectMethod().getResponseBodyAsString());
    }
}

From source file:com.joliciel.frenchTreebank.FrenchTreebank.java

/**
 * @param args/*from  w w w . j a va 2  s. c o m*/
 */
public static void main(String[] args) throws Exception {
    String command = args[0];

    String outFilePath = "";
    String outDirPath = "";
    String treebankPath = "";
    String ftbFileName = "";
    String rawTextDir = "";
    String queryPath = "";
    String sentenceNumber = null;
    boolean firstArg = true;
    for (String arg : args) {
        if (firstArg) {
            firstArg = false;
            continue;
        }
        int equalsPos = arg.indexOf('=');
        String argName = arg.substring(0, equalsPos);
        String argValue = arg.substring(equalsPos + 1);
        if (argName.equals("outfile"))
            outFilePath = argValue;
        else if (argName.equals("outdir"))
            outDirPath = argValue;
        else if (argName.equals("ftbFileName"))
            ftbFileName = argValue;
        else if (argName.equals("treebank"))
            treebankPath = argValue;
        else if (argName.equals("sentence"))
            sentenceNumber = argValue;
        else if (argName.equals("query"))
            queryPath = argValue;
        else if (argName.equals("rawTextDir"))
            rawTextDir = argValue;
        else
            throw new RuntimeException("Unknown argument: " + argName);
    }

    TalismaneServiceLocator talismaneServiceLocator = TalismaneServiceLocator.getInstance();

    TreebankServiceLocator locator = TreebankServiceLocator.getInstance(talismaneServiceLocator);

    if (treebankPath.length() == 0)
        locator.setDataSourcePropertiesFile("jdbc-live.properties");

    if (command.equals("search")) {
        final SearchService searchService = locator.getSearchService();
        final XmlPatternSearch search = searchService.newXmlPatternSearch();
        search.setXmlPatternFile(queryPath);
        List<SearchResult> searchResults = search.perform();

        FileWriter fileWriter = new FileWriter(outFilePath);
        for (SearchResult searchResult : searchResults) {
            String lineToWrite = "";
            Sentence sentence = searchResult.getSentence();
            Phrase phrase = searchResult.getPhrase();
            lineToWrite += sentence.getFile().getFileName() + "|";
            lineToWrite += sentence.getSentenceNumber() + "|";
            List<PhraseUnit> phraseUnits = searchResult.getPhraseUnits();
            LOG.debug("Phrase: " + phrase.getId());
            for (PhraseUnit phraseUnit : phraseUnits)
                lineToWrite += phraseUnit.getLemma().getText() + "|";
            lineToWrite += phrase.getText();
            fileWriter.write(lineToWrite + "\n");
        }
        fileWriter.flush();
        fileWriter.close();
    } else if (command.equals("load")) {
        final TreebankService treebankService = locator.getTreebankService();
        final TreebankSAXParser parser = new TreebankSAXParser();
        parser.setTreebankService(treebankService);
        parser.parseDocument(treebankPath);
    } else if (command.equals("loadAll")) {
        final TreebankService treebankService = locator.getTreebankService();

        File dir = new File(treebankPath);

        String firstFile = null;
        if (args.length > 2)
            firstFile = args[2];
        String[] files = dir.list();
        if (files == null) {
            throw new RuntimeException("Not a directory or no children: " + treebankPath);
        } else {
            boolean startProcessing = true;
            if (firstFile != null)
                startProcessing = false;
            for (int i = 0; i < files.length; i++) {
                if (!startProcessing && files[i].equals(firstFile))
                    startProcessing = true;
                if (startProcessing) {
                    String filePath = args[1] + "/" + files[i];
                    LOG.debug(filePath);
                    final TreebankSAXParser parser = new TreebankSAXParser();
                    parser.setTreebankService(treebankService);
                    parser.parseDocument(filePath);
                }
            }
        }
    } else if (command.equals("loadRawText")) {
        final TreebankService treebankService = locator.getTreebankService();
        final TreebankRawTextAssigner assigner = new TreebankRawTextAssigner();
        assigner.setTreebankService(treebankService);
        assigner.setRawTextDirectory(rawTextDir);
        assigner.loadRawText();
    } else if (command.equals("tokenize")) {
        Writer csvFileWriter = null;
        if (outFilePath != null && outFilePath.length() > 0) {
            if (outFilePath.lastIndexOf("/") > 0) {
                String outputDirPath = outFilePath.substring(0, outFilePath.lastIndexOf("/"));
                File outputDir = new File(outputDirPath);
                outputDir.mkdirs();
            }

            File csvFile = new File(outFilePath);
            csvFile.delete();
            csvFile.createNewFile();
            csvFileWriter = new BufferedWriter(
                    new OutputStreamWriter(new FileOutputStream(csvFile, false), "UTF8"));
        }
        try {

            final TreebankService treebankService = locator.getTreebankService();
            TreebankExportService treebankExportService = locator.getTreebankExportServiceLocator()
                    .getTreebankExportService();
            TreebankUploadService treebankUploadService = locator.getTreebankUploadServiceLocator()
                    .getTreebankUploadService();
            TreebankReader treebankReader = null;

            if (treebankPath.length() > 0) {
                File treebankFile = new File(treebankPath);
                if (sentenceNumber != null)
                    treebankReader = treebankUploadService.getXmlReader(treebankFile, sentenceNumber);
                else
                    treebankReader = treebankUploadService.getXmlReader(treebankFile);

            } else {
                treebankReader = treebankService.getDatabaseReader(TreebankSubSet.ALL, 0);
            }

            TokeniserAnnotatedCorpusReader reader = treebankExportService
                    .getTokeniserAnnotatedCorpusReader(treebankReader, csvFileWriter);

            while (reader.hasNextTokenSequence()) {
                TokenSequence tokenSequence = reader.nextTokenSequence();
                List<Integer> tokenSplits = tokenSequence.getTokenSplits();
                String sentence = tokenSequence.getText();
                LOG.debug(sentence);
                int currentPos = 0;
                StringBuilder sb = new StringBuilder();
                for (int split : tokenSplits) {
                    if (split == 0)
                        continue;
                    String token = sentence.substring(currentPos, split);
                    sb.append('|');
                    sb.append(token);
                    currentPos = split;
                }
                LOG.debug(sb.toString());
            }
        } finally {
            csvFileWriter.flush();
            csvFileWriter.close();
        }
    } else if (command.equals("export")) {
        if (outDirPath.length() == 0)
            throw new RuntimeException("Parameter required: outdir");
        File outDir = new File(outDirPath);
        outDir.mkdirs();

        final TreebankService treebankService = locator.getTreebankService();
        FrenchTreebankXmlWriter xmlWriter = new FrenchTreebankXmlWriter();
        xmlWriter.setTreebankService(treebankService);

        if (ftbFileName.length() == 0) {
            xmlWriter.write(outDir);
        } else {
            TreebankFile ftbFile = treebankService.loadTreebankFile(ftbFileName);
            String fileName = ftbFileName.substring(ftbFileName.lastIndexOf('/') + 1);
            File xmlFile = new File(outDir, fileName);
            xmlFile.delete();
            xmlFile.createNewFile();

            Writer xmlFileWriter = new BufferedWriter(
                    new OutputStreamWriter(new FileOutputStream(xmlFile, false), "UTF8"));
            xmlWriter.write(xmlFileWriter, ftbFile);
            xmlFileWriter.flush();
            xmlFileWriter.close();
        }
    } else {
        throw new RuntimeException("Unknown command: " + command);
    }
    LOG.debug("========== END ============");
}