Example usage for java.io BufferedWriter close

List of usage examples for java.io BufferedWriter close

Introduction

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

Prototype

@SuppressWarnings("try")
    public void close() throws IOException 

Source Link

Usage

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  . j a  va 2 s.  c  o m

        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[] 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   ww  w .  ja v 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: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);//from  w  ww. j  a  v a 2s.  com
            writer.newLine();
        }
        writer.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 {//from   ww  w  .  j  a  v a2 s.c om
        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:com.tmo.swagger.main.GenrateSwaggerJson.java

public static void main(String[] args)
        throws JsonGenerationException, JsonMappingException, IOException, EmptyXlsRows {

    PropertyReader pr = new PropertyReader();

    Properties prop = pr.readPropertiesFile(args[0]);
    //Properties prop =pr.readClassPathPropertyFile("common.properties");
    String swaggerFile = prop.getProperty("swagger.json");
    String sw = "";
    if (swaggerFile != null && swaggerFile.length() > 0) {
        Swagger swagger = populatePropertiesOnlyPaths(prop, new SwaggerParser().read(swaggerFile));
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(Include.NON_NULL);
        sw = mapper.writeValueAsString(swagger);
    } else {/*from  w w  w.j  av  a  2 s.  co m*/
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(Include.NON_NULL);
        Swagger swagger = populateProperties(prop);
        sw = mapper.writeValueAsString(swagger);
    }
    try {
        File file = new File(args[1] + prop.getProperty("path.operation.tags") + ".json");
        //File file = new File("src/main/resources/"+prop.getProperty("path.operation.tags")+".json");
        if (!file.exists()) {
            file.createNewFile();
        }
        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(sw);
        logger.info("Swagger Genration Done!");
        bw.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:eu.fbk.dkm.sectionextractor.PageClassMerger.java

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

    CommandLineWithLogger commandLineWithLogger = new CommandLineWithLogger();
    commandLineWithLogger.addOption(OptionBuilder.withArgName("file").hasArg()
            .withDescription("WikiData ID file").isRequired().withLongOpt("wikidata-id").create("i"));
    commandLineWithLogger.addOption(OptionBuilder.withArgName("file").hasArg()
            .withDescription("Airpedia Person file").isRequired().withLongOpt("airpedia").create("a"));
    commandLineWithLogger.addOption(OptionBuilder.withArgName("file").hasArg().withDescription("Output file")
            .isRequired().withLongOpt("output").create("o"));
    CommandLine commandLine = null;/*ww  w.j a v  a  2  s .  c o m*/
    try {
        commandLine = commandLineWithLogger.getCommandLine(args);
        PropertyConfigurator.configure(commandLineWithLogger.getLoggerProps());
    } catch (Exception e) {
        System.exit(1);
    }

    String wikiIDFileName = commandLine.getOptionValue("wikidata-id");
    String airpediaFileName = commandLine.getOptionValue("airpedia");
    String outputFileName = commandLine.getOptionValue("output");

    HashMap<Integer, String> wikiIDs = new HashMap<>();
    HashSet<Integer> airpediaClasses = new HashSet<>();

    List<String> strings;

    logger.info("Loading file " + wikiIDFileName);
    strings = Files.readLines(new File(wikiIDFileName), Charsets.UTF_8);
    for (String line : strings) {
        line = line.trim();
        if (line.length() == 0) {
            continue;
        }
        if (line.startsWith("#")) {
            continue;
        }

        String[] parts = line.split("\t");
        if (parts.length < 2) {
            continue;
        }

        int id;
        try {
            id = Integer.parseInt(parts[0]);
        } catch (Exception e) {
            continue;
        }
        wikiIDs.put(id, parts[1]);
    }

    logger.info("Loading file " + airpediaFileName);
    strings = Files.readLines(new File(airpediaFileName), Charsets.UTF_8);
    for (String line : strings) {
        line = line.trim();
        if (line.length() == 0) {
            continue;
        }
        if (line.startsWith("#")) {
            continue;
        }

        String[] parts = line.split("\t");
        if (parts.length < 2) {
            continue;
        }

        int id;
        try {
            id = Integer.parseInt(parts[0]);
        } catch (Exception e) {
            continue;
        }
        airpediaClasses.add(id);
    }

    logger.info("Saving information");
    BufferedWriter writer = new BufferedWriter(new FileWriter(outputFileName));
    for (int i : wikiIDs.keySet()) {
        if (!airpediaClasses.contains(i)) {
            continue;
        }

        writer.append(wikiIDs.get(i)).append("\n");
    }
    writer.close();
}

From source file:AllCapsDemo.java

License:asdf

public static void main(String[] arguments) {
    String sourceName = "asdf";
    try {/* w ww  .j av a 2s  .co  m*/
        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:it.sardegnaricerche.voiceid.sr.Voiceid.java

public static void main(String[] args) {
    logger.info("Voiceid main method");
    logger.info("First argument: '" + args[0] + "'");
    long startTime = System.currentTimeMillis();
    Voiceid voiceid = null;/*from  ww  w  .j  av  a2 s  . c o m*/
    GMMVoiceDB db = null;
    try {
        db = new GMMVoiceDB(args[1], new UBMModel(args[0]));
        File f = new File(args[2]);
        voiceid = new Voiceid(db, f, new LIUMStandardDiarizator());
        voiceid.extractClusters();
        voiceid.matchClusters();
        // voiceid.toWav();
        // voiceid.printClusters();
        JSONObject obj = voiceid.toJson();

        for (VCluster c : voiceid.getClusters()) {
            logger.info("" + c.getSample().getResource().getAbsolutePath());
        }

        // FileWriter fstream = new
        // FileWriter(f.getAbsolutePath().replaceFirst("[.][^.]+$", "") +
        // ".json");
        String filename = Utils.getBasename(f) + ".json";
        FileWriter fstream = new FileWriter(filename);
        BufferedWriter out = new BufferedWriter(fstream);
        out.write(obj.toString());
        // Close the output stream
        out.close();

        // voiceid.makeAllModels();
    } catch (IOException e) {
        logger.severe(e.getMessage());
    } catch (Exception ex) {
        logger.severe(ex.getMessage());
    }
    long endTime = System.currentTimeMillis();
    long duration = endTime - startTime;
    logger.info("Exit (" + ((float) duration / 1000) + " s)");
    // logger.info("Max Threads: " + (int) db.maxThreads);
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    BufferedReader br = new BufferedReader(new FileReader("in.txt"));
    BufferedWriter bw = new BufferedWriter(new FileWriter("out.txt"));
    int i;//from   w  w w . j  a  v a 2  s . c o m
    do {
        i = br.read();
        if (i != -1) {
            if (Character.isLowerCase((char) i))
                bw.write(Character.toUpperCase((char) i));
            else if (Character.isUpperCase((char) i))
                bw.write(Character.toLowerCase((char) i));
            else
                bw.write((char) i);
        }
    } while (i != -1);
    br.close();
    bw.close();
}

From source file:experiments.SimpleExample.java

/**
 * Starts the example.//  w ww .j a v 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();
    }

}