Example usage for java.io BufferedWriter flush

List of usage examples for java.io BufferedWriter flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes the stream.

Usage

From source file:eu.annocultor.converters.geonames.GeonamesDumpToRdf.java

public static void main(String[] args) throws Exception {
    File root = new File("input_source");

    // load country-continent match
    countryToContinent/*  ww  w  .  ja  v a2  s. co  m*/
            .load((new GeonamesDumpToRdf()).getClass().getResourceAsStream("/country-to-continent.properties"));

    // creating files
    Map<String, BufferedWriter> files = new HashMap<String, BufferedWriter>();
    Map<String, Boolean> started = new HashMap<String, Boolean>();

    for (Object string : countryToContinent.keySet()) {
        String continent = countryToContinent.getProperty(string.toString());
        File dir = new File(root, continent);
        if (!dir.exists()) {
            dir.mkdir();
        }
        files.put(string.toString(), new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(new File(root, continent + "/" + string + ".rdf")), "UTF-8")));
        System.out.println(continent + "/" + string + ".rdf");
        started.put(string.toString(), false);
    }

    System.out.println(started);

    Pattern countryPattern = Pattern
            .compile("<inCountry rdf\\:resource\\=\"http\\://www\\.geonames\\.org/countries/\\#(\\w\\w)\"/>");
    long counter = 0;
    LineIterator it = FileUtils.lineIterator(new File(root, "all-geonames-rdf.txt"), "UTF-8");
    try {
        while (it.hasNext()) {
            String text = it.nextLine();
            if (text.startsWith("http://sws.geonames"))
                continue;

            // progress
            counter++;
            if (counter % 100000 == 0) {
                System.out.print("*");
            }
            //         System.out.println(counter);
            // get country
            String country = null;
            Matcher matcher = countryPattern.matcher(text);
            if (matcher.find()) {
                country = matcher.group(1);
            }
            //         System.out.println(country);
            if (country == null)
                country = "null";
            text = text.replace("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><rdf:RDF",
                    "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><rdf:RDF");
            if (started.get(country) == null)
                throw new Exception("Unknow country " + country);
            if (started.get(country).booleanValue()) {
                // remove RDF opening
                text = text.substring(text.indexOf("<rdf:RDF "));
                text = text.substring(text.indexOf(">") + 1);
            }
            // remove RDF ending
            text = text.substring(0, text.indexOf("</rdf:RDF>"));
            files.get(country).append(text + "\n");
            if (!started.get(country).booleanValue()) {
                // System.out.println("Started with country " + country);
            }
            started.put(country, true);
        }
    } finally {
        LineIterator.closeQuietly(it);
    }

    for (Object string : countryToContinent.keySet()) {
        boolean hasStarted = started.get(string.toString()).booleanValue();
        if (hasStarted) {
            BufferedWriter bf = files.get(string.toString());
            bf.append("</rdf:RDF>");
            bf.flush();
            bf.close();
        }
    }
    return;
}

From source file:Test.java

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

  SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory
      .getDefault();// www  .  j  ava  2s  .  c om
  SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(
      "localhost", 9999);

  InputStreamReader inputStreamReader = new InputStreamReader(System.in);
  BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

  OutputStream outputStream = sslSocket.getOutputStream();
  OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
  BufferedWriter bufferedwriter = new BufferedWriter(outputStreamWriter);

  String line = null;
  while ((line = bufferedReader.readLine()) != null) {
    bufferedwriter.write(line + '\n');
    bufferedwriter.flush();
  }
}

From source file:ASCII2NATIVE.java

public static void main(String[] args) {
    File f = new File("c:\\mydb.script");
    File f2 = new File("c:\\mydb3.script");
    if (f.exists() && f.isFile()) {
        // convert param-file
        BufferedReader br = null;
        StringBuffer sb = new StringBuffer();
        String line;// www  .  ja  va 2  s . c  om

        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(f), "JISAutoDetect"));

            while ((line = br.readLine()) != null) {
                System.out.println(ascii2Native(line));
                sb.append(ascii2Native(line)).append(";\n");//.append(";\n\r")
            }

            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f2), "utf-8"));
            out.append(sb.toString());
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            System.err.println("file not found - " + f);
        } catch (IOException e) {
            System.err.println("read error - " + f);
        } finally {
            try {
                if (br != null)
                    br.close();
            } catch (Exception e) {
            }
        }
    } else {
        // // convert param-data
        // System.out.print(ascii2native(args[i]));
        // if (i + 1 < args.length)
        // System.out.print(' ');
    }
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");

    Socket socket = new Socket("127.0.0.1", 8080);

    String path = "/servlet";
    BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8"));
    wr.write("POST " + path + " HTTP/1.0\r\n");
    wr.write("Content-Length: " + data.length() + "\r\n");
    wr.write("Content-Type: application/x-www-form-urlencoded\r\n");
    wr.write("\r\n");

    wr.write(data);//www  . j  av a 2 s. c o  m
    wr.flush();

    BufferedReader rd = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    String line;
    while ((line = rd.readLine()) != null) {
        System.out.println(line);
    }
    wr.close();
    rd.close();
}

From source file:TabFilter.java

public static void main(String args[]) throws Exception {
    FileReader fr = new FileReader(args[0]);
    BufferedReader br = new BufferedReader(fr);

    FileWriter fw = new FileWriter(args[1]);
    BufferedWriter bw = new BufferedWriter(fw);

    // Convert tab to space characters
    String s;//from w  w w .  j  av a 2s .  co m
    while ((s = br.readLine()) != null) {
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == '\t')
                c = ' ';
            bw.write(c);
        }
    }

    bw.flush();
    fr.close();
    fw.close();
}

From source file:experiments.SimpleExample.java

/**
 * Starts the example.//from  w  ww.j  av a 2s.c  om
 * 
 * @param args
 *            if optional first argument provided, it represents the number
 *            of bits to use, but no more than 32
 * 
 * @author Neil Rotstan
 * @author Klaus Meffert
 * @throws IOException 
 * @since 2.0
 */
public static void main(String[] args) throws IOException {

    SimpleExample se = new SimpleExample();

    try {
        File[] result = { new File("ga_x.txt"), new File("ga_cos.txt"), new File("ga_ackley.txt"),
                new File("ga_quar.txt"), new File("ga_step.txt"), new File("ga_rosen.txt"),
                new File("ga_sch.txt"), new File("ga_gri.txt"), new File("ga_pen1.txt"),
                new File("ga_pen2.txt"), new File("ga_wei.txt"), new File("ga_non.txt") };
        BufferedWriter[] output = new BufferedWriter[result.length];
        for (int i = 0; i <= result.length - 1; i++) {
            if (result[i].exists()) {
                result[i].delete();
                if (result[i].createNewFile()) {
                    System.out.println("result" + i + " file create success!");
                } else {
                    System.out.println("result" + i + " file create failed!");
                }
            } else {
                if (result[i].createNewFile()) {
                    System.out.println("result" + i + " file create success!");
                } else {
                    System.out.println("result" + i + " file create failed!");
                }

            }
            output[i] = new BufferedWriter(new FileWriter(result[i]));
        }

        for (int a = 0; a <= 0; a++) {
            //            se.runga(100, 30, 40, -100,  100, new MaxFunction(), output[0]);
            //            se.runga(200, 30, 40, -100,  100, new MaxFunction(), output[0]);
            //            se.runga(120, 30, 40, -5.12,  5.12, new CosMaxFunction(), output[1]);
            //            se.runga(200, 30, 40, -5.12,  5.12, new CosMaxFunction(), output[1]);
            //            se.runga(120, 30, 40, -32,  32, new AckleyMaxFunction(), output[2]);
            se.runga(2000, 30, 40, -32, 32, new AckleyMaxFunction(), output[2]);
            //            se.runga(120, 30, 40, -100,  100, new QuardircMaxFunction(), output[3]);
            //            se.runga(200, 30, 40, -100,  100, new QuardircMaxFunction(), output[3]);
            //            se.runga(120, 30, 40, -100,  100, new StepMaxFunction(), output[4]);
            //            se.runga(200, 30, 40, -100,  100, new StepMaxFunction(), output[4]);
            //            se.runga(120, 30, 40, -30,  30, new RosenbrockMaxFunction(), output[5]);
            //            se.runga(200, 30, 40, -30,  30, new RosenbrockMaxFunction(), output[5]);
            //            se.runga(120, 30, 40, -500,  500, new SchwefelMaxFunction(), output[6]);
            //            se.runga(200, 30, 40, -500,  500, new SchwefelMaxFunction(), output[6]);
            //            se.runga(120, 30, 40, -600,  600, new GriewankMaxFunction(), output[7]);
            //            se.runga(200, 30, 40, -600,  600, new GriewankMaxFunction(), output[7]);
            //            se.runga(120, 30, 40, -50,  50, new PenalizedMaxFunction(), output[8]);
            //            se.runga(200, 30, 40, -50,  50, new PenalizedMaxFunction(), output[8]);
            //            se.runga(120, 30, 40, -50,  50, new Penalized2MaxFunction(), output[9]);
            //            se.runga(200, 30, 40, -50,  50, new Penalized2MaxFunction(), output[9]);
            //            se.runga(120, 30, 40, -5.12,  5.12, new WeiMaxFunction(), output[10]);
            //            se.runga(200, 30, 40, -5.12,  5.12, new WeiMaxFunction(), output[10]);
            //            se.runga(120, 30, 40, -0.5,  0.5, new NonMaxFunction(), output[11]);
            //            se.runga(200, 30, 40, -0.5,  0.5, new NonMaxFunction(), output[11]);
            for (BufferedWriter op : output) {
                op.write("\n");
                op.flush();
            }
        }

        for (BufferedWriter op : output) {
            op.close();
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:at.riemers.velocity2js.velocity.Velocity2Js.java

/**
 * @param args the command line arguments
 *//*w w  w .j  a v  a 2 s. c  o m*/
public static void main(String[] args) {
    try {
        if (args.length == 0) {
            printUsage();
            return;
        }

        if (args[0].equals("-d") && args.length >= 3) {
            String resource = null;
            if (args.length >= 4) {
                resource = args[3];
            }
            List<I18NBundle> bundles = getBundles(resource);

            Velocity2Js.generateDir(args[1], args[2], bundles);
            return;
        }

        if (args[0].equals("-f") && args.length >= 4) {

            Properties p = new Properties();
            p.setProperty("resource.loader", "file");

            p.setProperty("file.resource.loader.description", "Velocity File Resource Loader");
            p.setProperty("file.resource.loader.class",
                    "org.apache.velocity.runtime.resource.loader.FileResourceLoader");

            p.setProperty("file.resource.loader.path", args[1]);

            Velocity2Js.init(p);

            String function = createFunctionName(args[2]);
            String resource = null;
            if (args.length >= 5) {
                resource = args[4];
            }
            List<I18NBundle> bundles = getBundles(resource);

            for (I18NBundle bundle : bundles) {
                String fname = args[3];
                int e = args[3].lastIndexOf('.');
                if (e <= 0 || e > args[3].length())
                    e = args[3].length();
                fname = args[3].substring(0, e) + bundle.getLocale() + args[3].substring(e);

                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(new FileOutputStream(fname), "UTF8"));
                Velocity2Js.generate(args[2], function, writer, bundle.getBundle());
                writer.flush();
                writer.close();
            }

            return;
        }

        printUsage();
        return;

    } catch (ResourceNotFoundException rnfe) {
        log.error("[velocity2js] : cannot find template : " + rnfe.getMessage());
    } catch (ParseErrorException pee) {
        log.error("[velocity2js] :  Syntax error in template :" + pee);
    } catch (Exception ex) {
        System.out.flush();
        log.error("[velocity2js] :  unknown error " + ex.getMessage());
        ex.printStackTrace(System.out);
        System.out.println(ex.getLocalizedMessage());
        System.exit(1);
    }
}

From source file:com.cyberway.issue.net.PublicSuffixes.java

/**
 * Utility method for dumping a regex String, based on a published public
 * suffix list, which matches any SURT-form hostname up through the broadest
 * 'private' (assigned/sold) domain-segment. That is, for any of the
 * SURT-form hostnames.../*from  w ww .j ava2s. c  om*/
 * 
 * com,example, com,example,www, com,example,california,www
 * 
 * ...the regex will match 'com,example,'.
 * 
 * @param args
 * @throws IOException
 */
public static void main(String args[]) throws IOException {

    String regex;

    if (args.length == 0 || "=".equals(args[0])) {
        // use bundled list
        regex = getTopmostAssignedSurtPrefixRegex();
    } else {
        // use specified filename
        BufferedReader reader = new BufferedReader(new FileReader(args[0]));
        regex = getTopmostAssignedSurtPrefixRegex(reader);
        IOUtils.closeQuietly(reader);
    }

    boolean needsClose = false;
    BufferedWriter writer;
    if (args.length >= 2) {
        // writer to specified file
        writer = new BufferedWriter(new FileWriter(args[1]));
        needsClose = true;
    } else {
        // write to stdout
        writer = new BufferedWriter(new OutputStreamWriter(System.out));
    }
    writer.append(regex);
    writer.flush();
    if (needsClose) {
        writer.close();
    }
}

From source file:org.jfree.chart.demo.Display.java

/**
 * Launch the application.//from w  w  w. j  av  a 2  s.c  om
 */
public static void main(String[] args) throws IOException {

    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                Display window = new Display();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
            ////////////
        }
    });

    try {

        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String s;
        File dataFile = new File("data.txt");
        FileWriter fw = new FileWriter(dataFile);
        BufferedWriter bw = new BufferedWriter(fw);
        DataParser datIn = new DataParser(effectiveX, effectiveY);

        //while(!enabled){}//spin until enabled

        while ((s = in.readLine()) != null && s.length() != 0 && enabled) {
            // System.out.println(s);
            if (datIn.parseString(s)) {
                bw.write(s);
                bw.write('\n');
                bw.flush();
                panel_1.plotCoords(datIn.getX(), datIn.getFlippedY());
                TimeElapsed.setText(Double.toString(datIn.getTime()));
            }
        }

        bw.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:es.upm.dit.xsdinferencer.XSDInferencer.java

/**
 * Main method, executed when the tool is invoked as a standalone application
 * @param args an array with all the arguments passed to the application
 * @throws XSDConfigurationException if there is a problem regarding the configuration
 * @throws IOException if there is an I/O problem while reading the input XML files or writing the output files
 * @throws JDOMException if there is any problem while parsing the input XML files
 *///  w  w  w . j  a v  a2 s . c o m
public static void main(String[] args) throws Exception {
    if (Arrays.asList(args).contains("--help")) {
        printHelp();
        System.exit(0);
    }
    try {
        XSDInferencer inferencer = new XSDInferencer();

        Results results = inferencer.inferSchema(args);

        Map<String, String> xsdsAsXMLStrings = results.getXSDsAsStrings();
        Map<String, String> jsonsAsStrings = results.getJsonSchemasAsStrings();
        Map<String, String> schemasAsStrings = xsdsAsXMLStrings != null ? xsdsAsXMLStrings : jsonsAsStrings;
        Map<String, String> statisticsDocumentsAsXMLStrings = results.getStatisticsAsStrings();
        File outputDirectory = null;
        for (int i = 0; i < args.length; i++) {
            if (!args[i].equalsIgnoreCase("--" + KEY_OUTPUT_DIRECTORY))
                continue;
            if (args[i + 1].startsWith("--") || i == args.length - 1)
                throw new IllegalArgumentException("Output directory parameter bad specified");
            outputDirectory = new File(args[i + 1]);
            if (!outputDirectory.exists())
                throw new FileNotFoundException("Output directory not found.");
            if (!outputDirectory.isDirectory())
                throw new NotDirectoryException(outputDirectory.getPath());
        }
        if (outputDirectory != null) {
            System.out.println("Writing results to " + outputDirectory.getAbsolutePath());

            for (String name : schemasAsStrings.keySet()) {
                File currentOutpuFile = new File(outputDirectory, name);
                FileOutputStream fOs = new FileOutputStream(currentOutpuFile);
                BufferedWriter bWriter = new BufferedWriter(new OutputStreamWriter(fOs, Charsets.UTF_8));
                bWriter.write(schemasAsStrings.get(name));
                bWriter.flush();
                bWriter.close();
            }
            if (statisticsDocumentsAsXMLStrings != null) {
                for (String name : statisticsDocumentsAsXMLStrings.keySet()) {
                    File currentOutpuFile = new File(outputDirectory, name);
                    FileWriter fWriter = new FileWriter(currentOutpuFile);
                    BufferedWriter bWriter = new BufferedWriter(fWriter);
                    bWriter.write(statisticsDocumentsAsXMLStrings.get(name));
                    bWriter.flush();
                    bWriter.close();
                }
            }
            System.out.println("Results written");
        } else {
            for (String name : schemasAsStrings.keySet()) {
                System.out.println(name + ":");
                System.out.println(schemasAsStrings.get(name));
                System.out.println();
            }
            if (statisticsDocumentsAsXMLStrings != null) {
                for (String name : statisticsDocumentsAsXMLStrings.keySet()) {
                    System.out.println(name + ":");
                    System.out.println(statisticsDocumentsAsXMLStrings.get(name));
                    System.out.println();
                }
            }
        }
    } catch (XSDInferencerException e) {
        System.err.println();
        System.err.println("Error at inference proccess: " + e.getMessage());
        e.printStackTrace();
        System.exit(1);
    }
}