Example usage for java.io BufferedWriter write

List of usage examples for java.io BufferedWriter write

Introduction

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

Prototype

public void write(int c) throws IOException 

Source Link

Document

Writes a single character.

Usage

From source file:Test.java

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

  SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory
      .getDefault();/*from ww  w . j a  v a 2 s .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:it.sayservice.platform.smartplanner.utils.LegGenerator.java

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

    Mongo m = new Mongo("localhost"); // default port 27017
    DB db = m.getDB("smart-planner-15x");
    DBCollection coll = db.getCollection("stops");

    // read trips.txt(trips,serviceId).
    List<String[]> trips = readFileGetLines("src/main/resources/schedules/17/trips.txt");
    List<String[]> stopTimes = readFileGetLines("src/main/resources/schedules/17/stop_times.txt");
    for (String[] words : trips) {
        try {//from   w w w .j  a  v  a 2  s.  c  o  m
            String routeId = words[0].trim();
            String serviceId = words[1].trim();
            String tripId = words[2].trim();
            // fetch schedule for trips.
            for (int i = 0; i < stopTimes.size(); i++) {
                // already ordered by occurence.
                String[] scheduleLeg = stopTimes.get(i);
                if (scheduleLeg[0].equalsIgnoreCase(tripId)) {
                    // check if next leg belongs to same trip
                    if (stopTimes.get(i + 1)[0].equalsIgnoreCase(tripId)) {

                        String arrivalT = scheduleLeg[1];
                        String departT = scheduleLeg[2];
                        String sourceId = scheduleLeg[3];
                        String destId = stopTimes.get(i + 1)[3];
                        // get coordinates of stops.
                        /**
                         * make sure that mongo stop collection is
                         * populated. if, not, invoke
                         * http://localhost:7070/smart
                         * -planner/rest/getTransitTimes
                         * /TB_R2_R/1366776000000/1366819200000
                         */
                        Stop source = (Stop) getObjectByField(db, "id", sourceId, coll, Stop.class);
                        Stop destination = (Stop) getObjectByField(db, "id", destId, coll, Stop.class);
                        // System.out.println(tripId + ","
                        // + routeId + ","
                        // + source.getId() + ","
                        // + source.getLatitude() + ","
                        // + source.getLongitude() + ","
                        // + arrivalT + ","
                        // + destination.getId() + ","
                        // + destination.getLatitude() + ","
                        // + destination.getLongitude() + ","
                        // + departT + ","
                        // + serviceId
                        // );
                        String content = tripId + "," + routeId + "," + source.getStopId() + ","
                                + source.getLatitude() + "," + source.getLongitude() + "," + arrivalT + ","
                                + destination.getStopId() + "," + destination.getLatitude() + ","
                                + destination.getLongitude() + "," + departT + "," + "Giornaliero" + "\n";

                        File file = new File("src/main/resources/legs/legs.txt");
                        // single leg file
                        if (!file.exists()) {
                            file.createNewFile();
                        }

                        FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
                        BufferedWriter bw = new BufferedWriter(fw);
                        bw.write(content);
                        bw.close();
                        // individual trip leg file.
                        File fileT = new File("src/main/resources/legs/legs_" + routeId + ".txt");
                        FileWriter fwT = new FileWriter(fileT.getAbsoluteFile(), true);
                        BufferedWriter bwT = new BufferedWriter(fwT);
                        bwT.write(content);
                        bwT.close();

                    }
                }
            }

        } catch (Exception e) {
            System.out.println("Error parsing trip: " + words[0] + "," + words[1] + "," + words[2]);
        }
    }
    System.out.println("Done");
}

From source file:de.tudarmstadt.ukp.dkpro.keyphrases.wikipediafilter.filter.util.FileFilter.java

public static void main(String[] args) throws IOException {
    Set<String> articles = new HashSet<String>();
    articles.addAll(FileUtils.readLines(new File("target/wikipedia/articles.txt")));

    BufferedWriter writer = new BufferedWriter(new FileWriter(new File("target/passwords.txt.filtered")));
    for (String line : FileUtils.readLines(new File("target/passwords.txt"))) {
        if (articles.contains(line.split("\t")[0].toLowerCase())) {
            writer.write(line);
            writer.newLine();//from   w w  w  .j a  va  2 s  . c o  m
        }
        writer.close();
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    String pageAddr = "http://www.google.com/index.htm";
    URL url = new URL(pageAddr);
    String websiteAddress = url.getHost();

    String file = url.getFile();//from  w  w  w  . j  av  a 2  s  . c o m
    Socket clientSocket = new Socket(websiteAddress, 80);

    BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

    OutputStreamWriter outWriter = new OutputStreamWriter(clientSocket.getOutputStream());
    outWriter.write("GET " + file + " HTTP/1.0\r\n\n");
    outWriter.flush();
    BufferedWriter out = new BufferedWriter(new FileWriter(file));
    boolean more = true;
    String input;
    while (more) {
        input = inFromServer.readLine();
        if (input == null)
            more = false;
        else {
            out.write(input);
        }
    }
    out.close();
    clientSocket.close();
}

From source file:bookChapter.theoretical.AnalyzeTheoreticalMSMSCalculation.java

/**
 *
 * @param args//from   w  ww .ja v  a2  s . c  o  m
 * @throws IOException
 * @throws FileNotFoundException
 * @throws ClassNotFoundException
 * @throws InterruptedException
 * @throws MzMLUnmarshallerException
 */
public static void main(String[] args) throws IOException, FileNotFoundException, ClassNotFoundException,
        IOException, InterruptedException, MzMLUnmarshallerException {
    Logger l = Logger.getLogger("AnalyzeTheoreticalMSMSCalculation");
    Date date = Calendar.getInstance().getTime();
    DateFormat formatter = new SimpleDateFormat("EEEE, dd MMMM yyyy, hh:mm:ss.SSS a");
    String now = formatter.format(date);
    l.log(Level.INFO, "Calculation starts at {0}", now);
    double precursorTolerance = ConfigHolder.getInstance().getDouble("precursor.tolerance"),
            fragmentTolerance = ConfigHolder.getInstance().getDouble("fragment.tolerance");
    String databaseName = ConfigHolder.getInstance().getString("database.name"),
            spectraName = ConfigHolder.getInstance().getString("spectra.name"),
            output = ConfigHolder.getInstance().getString("output");
    int correctionFactor = ConfigHolder.getInstance().getInt("correctionFactor");
    boolean theoFromAllCharges = ConfigHolder.getInstance().getBoolean("hasAllPossCharge");
    BufferedWriter bw = new BufferedWriter(new FileWriter(output));
    bw.write("SpectrumTitle" + "\t" + "PrecursorMZ" + "\t" + "PrecursorCharge" + "\t" + "Observed Mass (M+H)"
            + "\t" + "AndromedaLikeScore" + "\t" + "SequestLikeScore" + "\t" + "PeptideByAndromedaLikeScore"
            + "\t" + "PeptideBySequestLikeScore" + "\t" + "LevenshteinDistance" + "\t" + "TotalScoredPeps"
            + "\t" + "isCorrectMatchByAndromedaLike" + "\t" + "isCorrectMatchBySequestLikeScore" + "\n");
    l.info("Getting database entries");
    // first load all sequences into the memory 
    HashSet<DBEntry> dbEntries = getDBEntries(databaseName);
    // for every spectrum-calculate both score...
    // now convert to binExperimental spectrum
    int num = 0;
    SpectrumFactory fct = SpectrumFactory.getInstance();
    num = 0;
    File f = new File(spectraName);
    if (spectraName.endsWith(".mgf")) {
        fct.addSpectra(f, new WaitingHandlerCLIImpl());
        l.log(Level.INFO, "Spectra scoring starts at {0}", now);
        for (String title : fct.getSpectrumTitles(f.getName())) {
            num++;
            MSnSpectrum ms = (MSnSpectrum) fct.getSpectrum(f.getName(), title);
            // here calculate all except this is an empty spectrum...
            if (ms.getPeakList().size() > 2) {
                // to check a spectrum with negative values..
                String text = result(ms, precursorTolerance, dbEntries, fragmentTolerance, correctionFactor,
                        theoFromAllCharges);
                if (!text.isEmpty()) {
                    bw.write(text);
                }
            }
            if (num % 500 == 0) {
                l.info("Running " + num + " spectra." + Calendar.getInstance().getTime());
            }
        }
    }
    l.info("Program finished at " + Calendar.getInstance().getTime());

    bw.close();
}

From source file:com.mapr.PurchaseLog.java

public static void main(String[] args) throws IOException {
    Options opts = new Options();
    CmdLineParser parser = new CmdLineParser(opts);
    try {/* w  ww .  ja  v  a  2s . com*/
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        System.err.println("Usage: -count <number>G|M|K [ -users number ]  log-file user-profiles");
        return;
    }

    Joiner withTab = Joiner.on("\t");

    // first generate lots of user definitions
    SchemaSampler users = new SchemaSampler(
            Resources.asCharSource(Resources.getResource("user-schema.txt"), Charsets.UTF_8).read());
    File userFile = File.createTempFile("user", "tsv");
    BufferedWriter out = Files.newBufferedWriter(userFile.toPath(), Charsets.UTF_8);
    for (int i = 0; i < opts.users; i++) {
        out.write(withTab.join(users.sample()));
        out.newLine();
    }
    out.close();

    // now generate a session for each user
    Splitter onTabs = Splitter.on("\t");
    Splitter onComma = Splitter.on(",");

    Random gen = new Random();
    SchemaSampler intermediate = new SchemaSampler(
            Resources.asCharSource(Resources.getResource("hit_step.txt"), Charsets.UTF_8).read());

    final int COUNTRY = users.getFieldNames().indexOf("country");
    final int CAMPAIGN = intermediate.getFieldNames().indexOf("campaign_list");
    final int SEARCH_TERMS = intermediate.getFieldNames().indexOf("search_keywords");
    Preconditions.checkState(COUNTRY >= 0, "Need country field in user schema");
    Preconditions.checkState(CAMPAIGN >= 0, "Need campaign_list field in step schema");
    Preconditions.checkState(SEARCH_TERMS >= 0, "Need search_keywords field in step schema");

    out = Files.newBufferedWriter(new File(opts.out).toPath(), Charsets.UTF_8);

    for (String line : Files.readAllLines(userFile.toPath(), Charsets.UTF_8)) {
        long t = (long) (TimeUnit.MILLISECONDS.convert(30, TimeUnit.DAYS) * gen.nextDouble());
        List<String> user = Lists.newArrayList(onTabs.split(line));

        // pick session length
        int n = (int) Math.floor(-30 * Math.log(gen.nextDouble()));

        for (int i = 0; i < n; i++) {
            // time on page
            int dt = (int) Math.floor(-20000 * Math.log(gen.nextDouble()));
            t += dt;

            // hit specific values
            JsonNode step = intermediate.sample();

            // check for purchase
            double p = 0.01;
            List<String> campaigns = Lists.newArrayList(onComma.split(step.get("campaign_list").asText()));
            List<String> keywords = Lists.newArrayList(onComma.split(step.get("search_keywords").asText()));
            if ((user.get(COUNTRY).equals("us") && campaigns.contains("5"))
                    || (user.get(COUNTRY).equals("jp") && campaigns.contains("7")) || keywords.contains("homer")
                    || keywords.contains("simpson")) {
                p = 0.5;
            }

            String events = gen.nextDouble() < p ? "1" : "-";

            out.write(Long.toString(t));
            out.write("\t");
            out.write(line);
            out.write("\t");
            out.write(withTab.join(step));
            out.write("\t");
            out.write(events);
            out.write("\n");
        }
    }
    out.close();
}

From source file:AllCapsDemo.java

License:asdf

public static void main(String[] arguments) {
    String sourceName = "asdf";
    try {//from  w ww  .  j  av a2 s  .  c om
        File source = new File(sourceName);
        File temp = new File("cap" + sourceName + ".tmp");

        FileReader fr = new FileReader(source);
        BufferedReader in = new BufferedReader(fr);

        FileWriter fw = new FileWriter(temp);
        BufferedWriter out = new BufferedWriter(fw);

        boolean eof = false;
        int inChar = 0;
        do {
            inChar = in.read();
            if (inChar != -1) {
                char outChar = Character.toUpperCase((char) inChar);
                out.write(outChar);
            } else
                eof = true;
        } while (!eof);
        in.close();
        out.close();

        boolean deleted = source.delete();
        if (deleted)
            temp.renameTo(source);
    } catch (Exception se) {
        System.out.println("Error - " + se.toString());
    }
}

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;/* w  w  w  .j av a 2  s . c  om*/
    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:BufferedCopy.java

public static void main(String[] args) throws IOException {
    BufferedReader inputStream = null;
    BufferedWriter outputStream = null;

    try {//from   w  ww  .  jav a  2 s . c o  m
        inputStream = new BufferedReader(new FileReader("xanadu.txt"));
        outputStream = new BufferedWriter(new FileWriter("characteroutput.txt"));

        int c;
        while ((c = inputStream.read()) != -1) {
            outputStream.write(c);
        }
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
        if (outputStream != null) {
            outputStream.close();
        }
    }
}

From source file:gobblin.runtime.util.JobStateToJsonConverter.java

@SuppressWarnings("all")
public static void main(String[] args) throws Exception {
    Option sysConfigOption = Option.builder("sc").argName("system configuration file")
            .desc("Gobblin system configuration file").longOpt("sysconfig").hasArgs().build();
    Option storeUrlOption = Option.builder("u").argName("gobblin state store URL")
            .desc("Gobblin state store root path URL").longOpt("storeurl").hasArgs().required().build();
    Option jobNameOption = Option.builder("n").argName("gobblin job name").desc("Gobblin job name")
            .longOpt("name").hasArgs().required().build();
    Option jobIdOption = Option.builder("i").argName("gobblin job id").desc("Gobblin job id").longOpt("id")
            .hasArgs().build();//from w  ww.  j  a  va  2s .  c  om
    Option convertAllOption = Option.builder("a")
            .desc("Whether to convert all past job states of the given job").longOpt("all").build();
    Option keepConfigOption = Option.builder("kc").desc("Whether to keep all configuration properties")
            .longOpt("keepConfig").build();
    Option outputToFile = Option.builder("t").argName("output file name").desc("Output file name")
            .longOpt("toFile").hasArgs().build();

    Options options = new Options();
    options.addOption(sysConfigOption);
    options.addOption(storeUrlOption);
    options.addOption(jobNameOption);
    options.addOption(jobIdOption);
    options.addOption(convertAllOption);
    options.addOption(keepConfigOption);
    options.addOption(outputToFile);

    CommandLine cmd = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cmd = parser.parse(options, args);
    } catch (ParseException pe) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("JobStateToJsonConverter", options);
        System.exit(1);
    }

    Properties sysConfig = new Properties();
    if (cmd.hasOption(sysConfigOption.getLongOpt())) {
        sysConfig = JobConfigurationUtils.fileToProperties(cmd.getOptionValue(sysConfigOption.getLongOpt()));
    }

    JobStateToJsonConverter converter = new JobStateToJsonConverter(sysConfig, cmd.getOptionValue('u'),
            cmd.hasOption("kc"));
    StringWriter stringWriter = new StringWriter();
    if (cmd.hasOption('i')) {
        converter.convert(cmd.getOptionValue('n'), cmd.getOptionValue('i'), stringWriter);
    } else {
        if (cmd.hasOption('a')) {
            converter.convertAll(cmd.getOptionValue('n'), stringWriter);
        } else {
            converter.convert(cmd.getOptionValue('n'), stringWriter);
        }
    }

    if (cmd.hasOption('t')) {
        Closer closer = Closer.create();
        try {
            FileOutputStream fileOutputStream = closer.register(new FileOutputStream(cmd.getOptionValue('t')));
            OutputStreamWriter outputStreamWriter = closer.register(
                    new OutputStreamWriter(fileOutputStream, ConfigurationKeys.DEFAULT_CHARSET_ENCODING));
            BufferedWriter bufferedWriter = closer.register(new BufferedWriter(outputStreamWriter));
            bufferedWriter.write(stringWriter.toString());
        } catch (Throwable t) {
            throw closer.rethrow(t);
        } finally {
            closer.close();
        }
    } else {
        System.out.println(stringWriter.toString());
    }
}