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:com.depas.utils.FileUtils.java

public static void writeTextToFile(String fileName, String contents) throws IOException {
    BufferedWriter out = null;
    try {//from w  ww . j  ava  2s .  c  o  m
        File outFile = new File(fileName);
        out = new BufferedWriter(new FileWriter(outFile));
        out.write(contents);
        out.close();
        out = null;
    } finally {
        if (out != null) {
            out.close();
        }
    }
}

From source file:edu.iu.daal_naive.NaiveUtil.java

static void generateTestPoints(int numOfDataPoints, int vectorSize, int nClasses, String localInputDir,
        FileSystem fs, Path dataDir) throws IOException, InterruptedException, ExecutionException {

    // Check data directory
    if (fs.exists(dataDir)) {
        fs.delete(dataDir, true);// ww w  .  ja  va 2 s. c o  m
    }
    // Check local directory
    File localDir = new File(localInputDir);
    // If existed, regenerate data
    if (localDir.exists() && localDir.isDirectory()) {
        for (File file : localDir.listFiles()) {
            file.delete();
        }
        localDir.delete();

    }
    boolean success = localDir.mkdir();
    if (success) {
        System.out.println("Directory: " + localInputDir + " created");
    }

    // generate test points
    BufferedWriter writer = new BufferedWriter(new FileWriter(localInputDir + File.separator + "testdata"));
    Random random = new Random();

    double point = 0;
    int label = 0;
    for (int i = 0; i < numOfDataPoints; i++) {
        for (int j = 0; j < vectorSize; j++) {
            point = random.nextDouble() * 2 - 1;
            writer.write(String.valueOf(point));
            writer.write(",");
        }

        label = random.nextInt(nClasses);
        writer.write(String.valueOf(label));
        writer.newLine();
    }

    writer.close();
    System.out.println("Write test data file");

    // Wrap to path object
    Path localInput = new Path(localInputDir);
    fs.copyFromLocalFile(localInput, dataDir);

}

From source file:DataBase.DatabaseManager.java

public static void writeKeywordsToFile(ArrayList<Book> books) {
    LOG.info("Keywords are writting to a file...");

    try {/*  ww w .j ava2s.  co m*/
        BufferedWriter out = new BufferedWriter(new FileWriter("file/keywords_output.txt", false));

        for (Book book : books) {
            for (int i = 0; i < book.getKeywords().size(); i++) {
                String line = book.getKeywords().get(i).getKeyword_id() + ";"
                        + book.getKeywords().get(i).getName();
                out.write(line);
                out.newLine();
            }

        }

        out.close();
    } catch (IOException e) {
    }
    LOG.info("Writting is done...");
}

From source file:edu.iu.daal_naive.NaiveUtil.java

static void generateGroundTruth(int numOfDataPoints, int nClasses, String localInputDir, FileSystem fs,
        Path dataDir) throws IOException, InterruptedException, ExecutionException {

    // Check data directory
    if (fs.exists(dataDir)) {
        fs.delete(dataDir, true);//from  ww w.  j  a v  a2  s .  c o m
    }
    // Check local directory
    File localDir = new File(localInputDir);
    // If existed, regenerate data
    if (localDir.exists() && localDir.isDirectory()) {
        for (File file : localDir.listFiles()) {
            file.delete();
        }
        localDir.delete();

    }
    boolean success = localDir.mkdir();
    if (success) {
        System.out.println("Directory: " + localInputDir + " created");
    }

    // generate test points
    BufferedWriter writer = new BufferedWriter(new FileWriter(localInputDir + File.separator + "groundtruth"));
    Random random = new Random();

    // double point = 0;
    int label = 0;
    for (int i = 0; i < numOfDataPoints; i++) {
        // for (int j = 0; j < vectorSize; j++) {
        //    point = random.nextDouble()*2 -1;
        //    writer.write(String.valueOf(point));
        //    writer.write(",");
        // }
        label = random.nextInt(nClasses);
        writer.write(String.valueOf(label));
        writer.newLine();
    }

    writer.close();
    System.out.println("Write groundtruth data file");

    // Wrap to path object
    Path localInput = new Path(localInputDir);
    fs.copyFromLocalFile(localInput, dataDir);

}

From source file:com.elastica.helper.FileUtility.java

/**
 * Saves HTML Source.//from   w  ww  .  j a  v a 2  s.co  m
 *
 * @param   path
 *
 * @throws  Exception
 */

public static void writeToFile(final String path, final String content) throws IOException {

    System.gc();

    FileOutputStream fileOutputStream = null;
    OutputStreamWriter outputStreamWriter = null;
    BufferedWriter bw = null;
    try {
        File parentDir = new File(path).getParentFile();
        if (!parentDir.exists()) {
            parentDir.mkdirs();
        }

        fileOutputStream = new FileOutputStream(path);
        outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF8");
        bw = new BufferedWriter(outputStreamWriter);
        bw.write(content);
    } finally {
        if (bw != null) {
            try {
                bw.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (outputStreamWriter != null) {
            try {
                outputStreamWriter.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (fileOutputStream != null) {
            try {
                fileOutputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.schnobosoft.semeval.cortical.PrintCorrelations.java

private static void saveCorrelations(File inputFile) throws IOException {
    assert inputFile.getName().startsWith(INPUT_FILE_PREFIX);
    File gsFile = new File(inputFile.getCanonicalPath().replace(INPUT_FILE_PREFIX, GS_FILE_PREFIX));
    List<Optional> gs = readScoresFile(gsFile);

    File targetFile = new File(inputFile.getCanonicalPath() + ".cortical.scores");
    BufferedWriter writer = new BufferedWriter(new FileWriter(targetFile));
    LOG.info("Writing scores to " + targetFile);

    for (Retina retinaName : Retina.values()) {
        for (Measure correlationMeasure : Measure.values()) {
            File outputFile = getOutputFile(inputFile, correlationMeasure, retinaName);
            if (outputFile.exists()) {
                List<Optional> scores = readScoresFile(outputFile);
                double pearson = getPearson(gs, scores);
                writer.write(String.format("Pearson correlation (%s, %s):\t%.4f%n",
                        retinaName.name().toLowerCase(), correlationMeasure, pearson));
            } else {
                LOG.warn("Output file not found: " + outputFile);
            }//from  w  ww  .  j a v  a 2 s.  c om
        }
    }
    writer.close();
}

From source file:com.photon.phresco.framework.commons.QualityUtil.java

private static void saveDocument(File file, Document doc) throws Exception {

    TransformerFactory factory1 = TransformerFactory.newInstance();
    Transformer transformer = factory1.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    StringWriter writer = new StringWriter();
    StreamResult result = new StreamResult(writer);
    DOMSource source = new DOMSource(doc);
    transformer.transform(source, result);
    String content = writer.toString();
    FileWriter fileWriter = new FileWriter(file);
    BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
    bufferedWriter.write(content);/*www.  j a  va2  s. c  o  m*/
    bufferedWriter.flush();
    bufferedWriter.close();
}

From source file:gamlss.utilities.MatrixFunctions.java

/**
 * Write matrix values to CSV file./*  w ww  .ja v  a  2 s .  co m*/
 * @param cmd - path to the file
 * @param m - matrix to write
 */
public static void matrixWriteCSV(final String cmd, final BlockRealMatrix m) {
    try {
        // Create file 
        FileWriter fstream = new FileWriter(cmd, false);
        BufferedWriter out = new BufferedWriter(fstream);

        for (int i = 0; i < m.getRowDimension(); i++) {
            for (int j = 0; j < m.getColumnDimension(); j++) {
                out.write(Double.toString(m.getEntry(i, j)));
                if (j < m.getColumnDimension() - 1) {
                    out.append(',');
                }
            }
            out.newLine();
        }
        out.close();
    } catch (Exception e) { //Catch exception if any
        System.err.println("Error: " + e.getMessage());
    }
}

From source file:Messenger.TorLib.java

public static void postToURL(String hostname, int port, String postKey, String data) throws IOException {
    Socket socket = TorSocket(hostname, port);
    SSLSocketFactory sslSf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    SSLSocket sslSocket = (SSLSocket) sslSf.createSocket(socket, null, socket.getPort(), false);
    sslSocket.setUseClientMode(true);/*  www  .j av a 2  s. c  o  m*/
    sslSocket.startHandshake();
    String path = "/" + postKey;
    BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(sslSocket.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);
    wr.flush();

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

From source file:com.revorg.goat.IndexManager.java

/**
 * Creates documents inside of the Lucene Index
 *
 * @param writer            Index Writer Class
 * @param rs                Result Set for the row of data
 * @param columnNamesArray  The array of column names to be added to the document
 * @param indexTypeArray    The array of column types to be added to the document
 * @param tempHTMLDir       The temporary HTML directory for HTML publishing
 * @throws Exception// www  . ja  v a 2  s . co m
 * @return ActionResult
 */
private static String createDocument(IndexWriter writer, ResultSet rs, String columnNamesArray[],
        String indexTypeArray[], String tempHTMLDir) {

    try {
        final Document doc = new Document();
        int columns = columnNamesArray.length;

        /*
        public Field(String name, String value, Field.Store store, Field.Index index)
        Store:
               COMPRESS - Store the original field value in the index in a compressed form. This is useful for long documents and for binary valued fields. 
               YES -Store the original field value in the index. This is useful for short texts like a document's title which should be displayed with the results. 
        The value is stored in its original form, i.e. no analyzer is used before it is stored. 
               NO - Do not store the field value in the index. 
                                                           
        Index:
               ANALYZED -  Index the tokens produced by running the field's value through an Analyzer. This is useful for common text
               NOT_ANALYZED - Index the field's value without using an Analyzer, so it can be searched. As no analyzer is used the value will be stored as a single term. 
        This is useful for unique Ids like product numbers.
               NO - Do not index the field value. This field can thus not be searched, but one can still access its contents provided it is stored. 
        */

        for (int i = 0; i < columns; i++) {
            String columnName = columnNamesArray[i].trim().toLowerCase();
            String columnIndexType = indexTypeArray[i]; //Map Column Type To Array
            String columnValue = rs.getString(columnName); //Get Value But Result Sets are at 1 Not 0
            if (columnValue == null) { //Lucene Does Not Like Nulls
                columnValue = "";
            }
            //System.out.println("   Values: " + columnName +  " " + columnIndexType + " " + columnValue + " " + columnValue.length());
            //Can't Add Triggers
            if (columnIndexType.equalsIgnoreCase("TriggerUpdate") == false
                    || columnIndexType.equalsIgnoreCase("TriggerDelete") == false) {
                if (columnIndexType.equalsIgnoreCase("PrimaryKey")
                        || columnIndexType.equalsIgnoreCase("Keyword")
                        || columnIndexType.equalsIgnoreCase("Date")) {
                    //Format Dates to Correct for Sorting
                    if (columnIndexType.equalsIgnoreCase("Date")) {
                        columnValue = columnValue.replace("/", "");
                    }

                    doc.add(new Field(columnName, columnValue, Field.Store.YES, Field.Index.NOT_ANALYZED));
                }
                //UnIndexed of UnIndexed
                else if (columnIndexType.equalsIgnoreCase("UnIndexed")) {
                    doc.add(new Field(columnName, columnValue, Field.Store.YES, Field.Index.NO));
                } else if (columnIndexType.equalsIgnoreCase("Text")) {
                    doc.add(new Field(columnName, columnValue, Field.Store.YES, Field.Index.ANALYZED));
                } else if (columnIndexType.equalsIgnoreCase("UnStored")
                        || columnIndexType.equalsIgnoreCase("HTML")) {
                    if (columnIndexType.equalsIgnoreCase("HTML") && columnValue.length() != 0) {
                        String htmlString = tempHTMLDir + Utilities.CreateUUID() + ".html";
                        File htmlFile = new File(htmlString);
                        BufferedWriter out = new BufferedWriter(new FileWriter(htmlString));
                        out.write(columnValue);
                        out.close();

                        //Parse Document              
                        FileInputStream fis = new FileInputStream(htmlFile);
                        HTMLParser parser = new HTMLParser(fis);
                        // Add the tag-stripped contents as a Reader-valued Text field so it will
                        // get tokenized and indexed.
                        doc.add(new Field(columnName, parser.getReader()));

                        //Parse HTML
                    }
                    //UnStored Field
                    else {
                        doc.add(new Field(columnName, columnValue, Field.Store.NO, Field.Index.ANALYZED));
                    }

                } else if (columnIndexType.equalsIgnoreCase("Binary")) {
                    doc.add(new Field(columnName, columnValue, Field.Store.COMPRESS, Field.Index.NO));
                }
            }
        }

        //Add Document Here
        //System.out.println(doc); 
        writer.addDocument(doc);
        ActionResult = "Success";
        return ActionResult;

    }

    catch (Exception e) {
        ActionResultError = " caught a " + e.getClass() + " with message: " + e.getMessage();
        //System.out.println("Failure of DbSchema File: " + xmlFile);
    }
    ActionResult = "Failure";
    return ActionResult + ActionResultError;
}