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:org.lieuofs.extraction.commune.historisation.ExtractionNumHistorisationCommune.java

/**
 * @param args// w ww. j  a  v a2s  .com
 */
public static void main(String[] args) throws IOException {
    ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "beans_lieuofs.xml" });
    CommuneCritere critere = new CommuneCritere();
    IGestionCommune gestionnaire = (IGestionCommune) context.getBean("gestionCommune");
    List<ICommuneSuisse> communes = gestionnaire.rechercher(critere);
    Collections.sort(communes, new Comparator<ICommuneSuisse>() {
        public int compare(ICommuneSuisse com1, ICommuneSuisse com2) {
            return com1.getNumeroOFS() - com2.getNumeroOFS();
        }
    });

    BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream("NumeroHistorisationCommune.sql"), "Windows-1252"));
    NumeroHistorisationCommuneWriter commWriter = new NumeroHistorisationRefonteSQLWriter();
    for (ICommuneSuisse commune : communes) {
        String numHistStr = commWriter.ecrireNumero(commune);
        if (null != numHistStr) {
            writer.append(numHistStr);
        }
    }
    writer.close();

}

From source file:BufferedCopy.java

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

    try {/*from ww w .  j  av  a2 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:de.jetwick.snacktory.HtmlFetcher.java

public static void main(String[] args) throws Exception {
    BufferedReader reader = new BufferedReader(new FileReader("urls.txt"));
    String line = null;/*from  ww  w  . j a va  2s  . c  o  m*/
    Set<String> existing = new LinkedHashSet<String>();
    while ((line = reader.readLine()) != null) {
        int index1 = line.indexOf("\"");
        int index2 = line.indexOf("\"", index1 + 1);
        String url = line.substring(index1 + 1, index2);
        String domainStr = SHelper.extractDomain(url, true);
        String counterStr = "";
        // TODO more similarities
        if (existing.contains(domainStr))
            counterStr = "2";
        else
            existing.add(domainStr);

        String html = new HtmlFetcher().fetchAsString(url, 20000);
        String outFile = domainStr + counterStr + ".html";
        BufferedWriter writer = new BufferedWriter(new FileWriter(outFile));
        writer.write(html);
        writer.close();
    }
    reader.close();
}

From source file:com.termmed.sampling.ConceptsWithMoreThanThreeRoleGroups.java

/**
 * The main method.//from   w w w. j av a  2s  .c  o m
 *
 * @param args the arguments
 * @throws Exception the exception
 */
public static void main(String[] args) throws Exception {
    System.out.println("Starting...");
    Map<String, Set<String>> groupsMap = new HashMap<String, Set<String>>();
    File relsFile = new File(
            "/Users/alo/Downloads/SnomedCT_RF2Release_INT_20160131-1/Snapshot/Terminology/sct2_Relationship_Snapshot_INT_20160131.txt");
    BufferedReader br2 = new BufferedReader(new FileReader(relsFile));
    String line2;
    int count2 = 0;
    while ((line2 = br2.readLine()) != null) {
        // process the line.
        count2++;
        if (count2 % 10000 == 0) {
            //System.out.println(count2);
        }
        List<String> columns = Arrays.asList(line2.split("\t", -1));
        if (columns.size() >= 6) {
            if (columns.get(2).equals("1") && !columns.get(6).equals("0")) {
                if (!groupsMap.containsKey(columns.get(4))) {
                    groupsMap.put(columns.get(4), new HashSet<String>());
                }
                groupsMap.get(columns.get(4)).add(columns.get(6));
            }
        }
    }
    System.out.println("Relationship groups loaded");
    Gson gson = new Gson();
    System.out.println("Reading JSON 1");
    File crossoverFile1 = new File("/Users/alo/Downloads/crossover_role_to_group.json");
    String contents = FileUtils.readFileToString(crossoverFile1, "utf-8");
    Type collectionType = new TypeToken<Collection<ControlResultLine>>() {
    }.getType();
    List<ControlResultLine> lineObject = gson.fromJson(contents, collectionType);
    Set<String> crossovers1 = new HashSet<String>();
    for (ControlResultLine loopResult : lineObject) {
        crossovers1.add(loopResult.conceptId);
    }
    System.out.println("Crossovers 1 loaded, " + lineObject.size() + " Objects");

    System.out.println("Reading JSON 2");
    File crossoverFile2 = new File("/Users/alo/Downloads/crossover_group_to_group.json");
    String contents2 = FileUtils.readFileToString(crossoverFile2, "utf-8");
    List<ControlResultLine> lineObject2 = gson.fromJson(contents2, collectionType);
    Set<String> crossovers2 = new HashSet<String>();
    for (ControlResultLine loopResult : lineObject2) {
        crossovers2.add(loopResult.conceptId);
    }
    System.out.println("Crossovers 2 loaded, " + lineObject2.size() + " Objects");

    Set<String> foundConcepts = new HashSet<String>();
    int count3 = 0;
    BufferedWriter writer = new BufferedWriter(
            new FileWriter(new File("ConceptsWithMoreThanThreeRoleGroups.csv")));
    ;
    for (String loopConcept : groupsMap.keySet()) {
        if (groupsMap.get(loopConcept).size() > 3) {
            writer.write(loopConcept);
            writer.newLine();
            foundConcepts.add(loopConcept);
            count3++;
        }
    }
    writer.close();
    System.out.println("Found " + foundConcepts.size() + " concepts");

    int countCrossover1 = 0;
    for (String loopConcept : foundConcepts) {
        if (crossovers1.contains(loopConcept)) {
            countCrossover1++;
        }
    }
    System.out.println(countCrossover1 + " are present in crossover_role_to_group");

    int countCrossover2 = 0;
    for (String loopConcept : foundConcepts) {
        if (crossovers2.contains(loopConcept)) {
            countCrossover2++;
        }
    }
    System.out.println(countCrossover2 + " are present in crossover_group_to_group");

    System.out.println("Done");
}

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);/*from   w ww  . j a v  a2 s.  c om*/
    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:at.riemers.velocity2js.velocity.Velocity2Js.java

/**
 * @param args the command line arguments
 *///ww w.j a va 2 s. co 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:FileCompressor.java

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

    String file = "D:\\XJad.rar.txt";
    BufferedReader reader = new BufferedReader(new FileReader(file));
    BufferedWriter writer = new BufferedWriter(new FileWriter(file + "_out.txt"));
    StringBuilder content = new StringBuilder();
    String tmp;// w w w .j av a  2 s  .  c om

    while ((tmp = reader.readLine()) != null) {
        content.append(tmp);
        content.append(System.getProperty("line.separator"));
    }

    FileCompressor f = new FileCompressor();
    writer.write(f.compress(content.toString()));

    writer.close();
    reader.close();

    reader = new BufferedReader(new FileReader(file + "_out.txt"));
    StringBuilder content2 = new StringBuilder();

    while ((tmp = reader.readLine()) != null) {
        content2.append(tmp);
        content2.append(System.getProperty("line.separator"));
    }

    String decompressed = f.decompress(content2.toString());
    String c = content.toString();
    System.out.println(decompressed.equals(c));
}

From source file:akori.Impact.java

static public void main(String[] args) throws IOException {
    String PATH = "E:\\Trabajos\\AKORI\\datosmatrizgino\\";
    String PATHIMG = "E:\\NetBeansProjects\\AKORI\\Proccess_1\\ImagesPages\\";
    for (int i = 1; i <= 32; ++i) {
        for (int k = 1; k <= 15; ++k) {
            System.out.println("Matrix " + i + "-" + k);
            BufferedImage img = null;
            try {
                img = ImageIO.read(new File(PATHIMG + i + ".png"));
            } catch (IOException ex) {
                ex.getStackTrace();//www.  ja va 2s .  c om
            }

            int ymax = img.getHeight();
            int xmax = img.getWidth();

            double[][] imagen = new double[ymax][xmax];

            BufferedReader in = null;
            try {
                in = new BufferedReader(new FileReader(PATH + i + "-" + k + ".txt"));
            } catch (FileNotFoundException ex) {
                ex.getStackTrace();
            }

            String linea;
            ArrayList<String> lista = new ArrayList<String>();
            HashMap<String, String> lista1 = new HashMap<String, String>();
            try {
                for (int j = 0; (linea = in.readLine()) != null; ++j) {
                    String[] datos = linea.split(",");
                    int x = (int) Double.parseDouble(datos[1]);
                    int y = (int) Double.parseDouble(datos[2]);
                    if (x >= xmax || y >= ymax || x <= 0 || y <= 0) {
                        continue;
                    }
                    lista.add(x + "," + y);
                }
            } catch (Exception ex) {
                ex.getStackTrace();
            }

            try {
                in.close();
            } catch (IOException ex) {
                ex.getStackTrace();
            }

            Iterator iter = lista.iterator();
            int[][] matrix = new int[lista.size()][2];

            for (int j = 0; iter.hasNext(); ++j) {
                String xy = (String) iter.next();
                String[] datos = xy.split(",");
                matrix[j][0] = Integer.parseInt(datos[0]);
                matrix[j][1] = Integer.parseInt(datos[1]);
            }

            for (int j = 0; j < matrix.length; ++j) {

                int std = 50;
                int x = matrix[j][0];
                int y = matrix[j][1];
                imagen[y][x] += 1;
                double aux;
                normalMatrix(imagen, y, x, std);

            }

            FileWriter fw = new FileWriter(PATH + "Matrix" + i + "-" + k + ".txt");
            BufferedWriter bw = new BufferedWriter(fw);
            for (int j = 0; j < imagen.length; ++j) {
                for (int t = 0; t < imagen[j].length; ++t) {
                    if (t + 1 == imagen[j].length)
                        bw.write(imagen[j][t] + "");
                    else
                        bw.write(imagen[j][t] + ",");
                }
                bw.write("\n");
            }
            bw.close();
        }
    }
}

From source file:com.cloud.utils.crypt.EncryptionSecretKeyChanger.java

public static void main(String[] args) {
    List<String> argsList = Arrays.asList(args);
    Iterator<String> iter = argsList.iterator();
    String oldMSKey = null;/*from  w w w .  jav a 2s . com*/
    String oldDBKey = null;
    String newMSKey = null;
    String newDBKey = null;

    //Parse command-line args
    while (iter.hasNext()) {
        String arg = iter.next();
        // Old MS Key
        if (arg.equals("-m")) {
            oldMSKey = iter.next();
        }
        // Old DB Key
        if (arg.equals("-d")) {
            oldDBKey = iter.next();
        }
        // New MS Key
        if (arg.equals("-n")) {
            newMSKey = iter.next();
        }
        // New DB Key
        if (arg.equals("-e")) {
            newDBKey = iter.next();
        }
    }

    if (oldMSKey == null || oldDBKey == null) {
        System.out.println("Existing MS secret key or DB secret key is not provided");
        usage();
        return;
    }

    if (newMSKey == null && newDBKey == null) {
        System.out.println("New MS secret key and DB secret are both not provided");
        usage();
        return;
    }

    final File dbPropsFile = PropertiesUtil.findConfigFile("db.properties");
    final Properties dbProps;
    EncryptionSecretKeyChanger keyChanger = new EncryptionSecretKeyChanger();
    StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
    keyChanger.initEncryptor(encryptor, oldMSKey);
    dbProps = new EncryptableProperties(encryptor);
    PropertiesConfiguration backupDBProps = null;

    System.out.println("Parsing db.properties file");
    try {
        dbProps.load(new FileInputStream(dbPropsFile));
        backupDBProps = new PropertiesConfiguration(dbPropsFile);
    } catch (FileNotFoundException e) {
        System.out.println("db.properties file not found while reading DB secret key" + e.getMessage());
    } catch (IOException e) {
        System.out.println("Error while reading DB secret key from db.properties" + e.getMessage());
    } catch (ConfigurationException e) {
        e.printStackTrace();
    }

    String dbSecretKey = null;
    try {
        dbSecretKey = dbProps.getProperty("db.cloud.encrypt.secret");
    } catch (EncryptionOperationNotPossibleException e) {
        System.out.println("Failed to decrypt existing DB secret key from db.properties. " + e.getMessage());
        return;
    }

    if (!oldDBKey.equals(dbSecretKey)) {
        System.out.println("Incorrect MS Secret Key or DB Secret Key");
        return;
    }

    System.out.println("Secret key provided matched the key in db.properties");
    final String encryptionType = dbProps.getProperty("db.cloud.encryption.type");

    if (newMSKey == null) {
        System.out.println("No change in MS Key. Skipping migrating db.properties");
    } else {
        if (!keyChanger.migrateProperties(dbPropsFile, dbProps, newMSKey, newDBKey)) {
            System.out.println("Failed to update db.properties");
            return;
        } else {
            //db.properties updated successfully
            if (encryptionType.equals("file")) {
                //update key file with new MS key
                try {
                    FileWriter fwriter = new FileWriter(keyFile);
                    BufferedWriter bwriter = new BufferedWriter(fwriter);
                    bwriter.write(newMSKey);
                    bwriter.close();
                } catch (IOException e) {
                    System.out.println("Failed to write new secret to file. Please update the file manually");
                }
            }
        }
    }

    boolean success = false;
    if (newDBKey == null || newDBKey.equals(oldDBKey)) {
        System.out.println("No change in DB Secret Key. Skipping Data Migration");
    } else {
        EncryptionSecretKeyChecker.initEncryptorForMigration(oldMSKey);
        try {
            success = keyChanger.migrateData(oldDBKey, newDBKey);
        } catch (Exception e) {
            System.out.println("Error during data migration");
            e.printStackTrace();
            success = false;
        }
    }

    if (success) {
        System.out.println("Successfully updated secret key(s)");
    } else {
        System.out.println("Data Migration failed. Reverting db.properties");
        //revert db.properties
        try {
            backupDBProps.save();
        } catch (ConfigurationException e) {
            e.printStackTrace();
        }
        if (encryptionType.equals("file")) {
            //revert secret key in file
            try {
                FileWriter fwriter = new FileWriter(keyFile);
                BufferedWriter bwriter = new BufferedWriter(fwriter);
                bwriter.write(oldMSKey);
                bwriter.close();
            } catch (IOException e) {
                System.out.println("Failed to revert to old secret to file. Please update the file manually");
            }
        }
    }
}

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...// ww  w  . j a  v a  2 s.c  o  m
 * 
 * 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();
    }
}