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:dk.clarin.tools.workflow.java

public static void got200(String result, bracmat BracMat, String filename, String jobID, InputStream input) {
    logger.debug("got200");
    /**//from www  . j  a v  a  2  s . c o m
     * toolsdata$
     *
     * Return the full file system path to Tool's staging area.
     * The input can be a file name: this name is appended to the returned value.
     */
    String destdir = BracMat.Eval("toolsdata$");
    /**
     * toolsdataURL$
     *
     * Return the full URL to Tool's staging area.
     * The input can be a file name: this name is appended to the returned value.
     */
    //String toolsdataURL = BracMat.Eval("toolsdataURL$");
    try {
        byte[] buffer = new byte[4096];
        int n = -1;
        int N = 0;
        //int Nbuf = 0;
        OutputStream outputF = new FileOutputStream(destdir + FilenameNoMetadata(filename));
        StringWriter outputM = new StringWriter();

        boolean isTextual = false;
        String textable = BracMat.Eval("getJobArg$(" + result + "." + jobID + ".isText)");
        if (textable.equals("y"))
            isTextual = true;
        logger.debug("textable:" + (isTextual ? "ja" : "nej"));

        while ((n = input.read(buffer)) != -1) {
            if (n > 0) {
                N = N + n;
                //++Nbuf;
                outputF.write(buffer, 0, n);
                if (isTextual) {
                    String toWrite = new String(buffer, 0, n);
                    try {
                        outputM.write(toWrite);
                    } catch (Exception e) {
                        logger.error("Could not write to StringWriter. Reason:" + e.getMessage());
                    }
                }
            }
        }
        outputF.close();
        String requestResult = outputM.toString();

        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String date = sdf.format(cal.getTime());
        logger.debug("Calling doneJob(" + result + "," + jobID + "," + date + ")");
        /**
         * doneJob$
         *
         * Marks a job as 'done' in jobs.table in jboss/server/default/data/tools
         * Constructs a CTBID from date, JobNr and jobID
         * Makes sure there is a row in table CTBs connecting
         *      JobNr, jobID, email and CTBID
         * Creates isDependentOf and isAnnotationOf relations
         * Affected tables:
         *      jobs.table
         *      CTBs.table
         *      relations.table
         * Arguments: jobNR, JobID, spangroup with annotation and date. 
         *
         * Notice that this function currently only can generate output of type 
         * TEIDKCLARIN_ANNO
         */
        String newResource = BracMat.Eval(
                "doneJob$(" + result + "." + jobID + "." + quote(requestResult) + "." + quote(date) + ")");
        // Create file plus metadata
        logger.debug("Going to write {}", destdir + Filename(filename));
        FileWriter fstream = new FileWriter(destdir + Filename(filename));
        BufferedWriter Out = new BufferedWriter(fstream);
        Out.write(newResource);
        Out.close();
        /**
         * relationFile$
         *
         * Create a relation file ready for deposition together with an annotation.
         *
         * Input: JobNr and jobID
         * Output: String that can be saved as a semicolon separated file.
         * Consulted tables:
         *      relations.table     (for relation type, ctb and ctbid
         *      CTBs.table          (for ContentProvider and CTBID)
         */
        String relations = BracMat.Eval("relationFile$(" + result + "." + jobID + ")");
        // Create relation file
        fstream = new FileWriter(destdir + FilenameRelations(filename));
        Out = new BufferedWriter(fstream);
        Out.write(relations);
        Out.close();
    } catch (Exception e) {//Catch exception if any
        logger.error("Could not write result to file. Aborting job " + jobID + ". Reason:" + e.getMessage());
        /**
         * abortJob$
         *
         * Abort, given a JobNr and a jobID, the specified job and all
         * pending jobs that depend on the output from the (now aborted) job.
         * Rather than removing the aborted jobs from the jobs.table list, they are
         * marked 'aborted'.
         * Result (as XML): a list of (JobNr, jobID, toolName, items)
         */
        /*filelist =*/ BracMat.Eval("abortJob$(" + result + "." + jobID + ")");
    }
}

From source file:LVCoref.MMAX2.java

public static void exportWords(Document d, String filename) {
    BufferedWriter writer = null;
    try {//from ww w .  j a  v a  2s  .  c  o m
        writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename), "UTF-8"));
    } catch (java.io.IOException ex) {
        ex.printStackTrace();
    }
    Utils.toWriter(writer, "<?xml version=\"1.0\" encoding=\"" + "UTF-8" + "\"?>\n"
            + "<!DOCTYPE words SYSTEM \"words.dtd\">\n" + "<words>\n");

    for (Node n : d.tree) {
        Utils.toWriter(writer,
                "<word id=\"word_" + (n.id + 1) + "\">" + StringEscapeUtils.escapeXml(n.word) + "</word>\n");
    }
    Utils.toWriter(writer, "</words>");
    try {
        writer.flush();
        writer.close();
    } catch (IOException ex) {
        Logger.getLogger(Document.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:funcoes.funcoes.java

public static void geraLog(String nome, String log) {

    int dia, mes, ano;
    String data_log;//from w  w w  .  j  a  va  2s .  c  om
    Calendar data;
    data = Calendar.getInstance();
    dia = data.get(Calendar.DAY_OF_MONTH);
    mes = data.get(Calendar.MONTH);
    ano = data.get(Calendar.YEAR);
    data_log = +dia + "_" + (mes + 1) + "_" + ano;
    if (dia < 10 && mes < 10) {
        data_log = "0" + dia + "_0" + (mes + 1) + "_" + ano;
    } else if (dia < 10 && mes >= 10) {
        data_log = "0" + dia + "_" + (mes + 1) + "_" + ano;
    } else if (dia >= 10 && mes < 10) {
        data_log = dia + "_0" + (mes + 1) + "_" + ano;
    } else {
        data_log = dia + "_" + (mes + 1) + "_" + ano;
    }

    File arquivo = new File("C:/SOVIONG/log/log_" + data_log + ".txt");

    try {
        if (!arquivo.exists()) {
            //cria um arquivo (vazio)
            arquivo.createNewFile();
        }

        //caso seja um diretrio,  possvel listar seus arquivos e diretrios
        //File[] arquivos = arquivo.listFiles();
        //escreve no arquivo
        FileWriter fw = new FileWriter(arquivo, true);
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(log + " "
                + data.getTime().toLocaleString().substring(10, data.getTime().toLocaleString().length())
                + " do dia: " + data.getTime().toLocaleString().substring(0, 10));
        bw.newLine();
        bw.close();
        fw.close();

    } catch (IOException ex) {
        JOptionPane.showMessageDialog(null, ex.getMessage());
    }

}

From source file:com.tactfactory.harmony.utils.TactFileUtils.java

/** Write StringBuffer contents to the given file.
 * @param buff The buffer to write to the file
 * @param file The file in which the buffer must be copied
 *//*from w w w. jav a 2s.  com*/
public static void stringBufferToFile(final StringBuffer buff, final File file) {
    FileOutputStream fos = null;
    OutputStreamWriter out = null;
    BufferedWriter bw = null;
    try {
        fos = new FileOutputStream(file);
        out = new OutputStreamWriter(fos, TactFileUtils.DEFAULT_ENCODING);
        bw = new BufferedWriter(out);
        bw.write(buff.toString());

    } catch (final IOException e) {
        ConsoleUtils.displayError(e);
    } finally {
        try {
            if (bw != null) {
                bw.close();
            }
            if (out != null) {
                out.close();
            }
            if (fos != null) {
                fos.close();
            }
        } catch (final IOException e) {
            ConsoleUtils.displayError(e);
        }
    }
}

From source file:com.almarsoft.GroundhogReader.lib.FSUtils.java

public static void writeReaderToDiskFile(Reader data, String fullPath, String fileName) throws IOException {

    File outDir = new File(fullPath);

    if (!outDir.exists())
        outDir.mkdirs();/*from  w ww .  j  a  v a2 s.c  o m*/

    BufferedWriter out = null;

    try {
        FileWriter writer = new FileWriter(fullPath + fileName);
        out = new BufferedWriter(writer);

        String readData = null;
        char[] buf = new char[1024];
        int numRead = 0;

        while ((numRead = data.read(buf)) != -1) {
            readData = String.valueOf(buf, 0, numRead);
            out.write(readData);
            buf = new char[1024];
        }

        //out.write(data);
        out.flush();
    } finally {
        if (out != null)
            out.close();
    }
}

From source file:gov.nih.nci.cabig.caaers.utils.CaaersSerializerUtil.java

/**
 * This method writes given content to a xml file. Location of the file is $CATALINA_HOME/logs/serializedfiles/
 * @param serializedContent//  w ww.  ja  va 2  s  .co  m
 */
public static void dumpContentToFile(String content) {
    BufferedWriter out = null;
    StringBuilder sb = null;
    try {
        if (StringUtils.isEmpty(CATALINA_HOME)) {
            sb = new StringBuilder(USER_HOME);
        } else {
            sb = new StringBuilder(System.getenv("CATALINA_HOME"));
            sb.append("/logs");
        }
        sb.append("/serializedfiles");
        File file = new File(sb.toString());
        if (!file.isDirectory()) {
            file.mkdir();
        }
        sb.append("/session_").append(System.currentTimeMillis()).append(".xml");
        out = new BufferedWriter(new FileWriter(sb.toString()));
        out.write(content);
    } catch (Exception e) {
        logger.error("Exception while writing contect to file -- ", e);
    } finally {
        try {
            out.close();
        } catch (Exception e) {
        }
    }
}

From source file:com.oocl.euc.ita.core.utils.FileUtils.java

public static void writefile(String path, String content, boolean append) {
    BufferedWriter bw;
    File targetFile;/*  www.  j a  va  2s  . c o m*/
    try {
        targetFile = new File(path);
        if (targetFile.exists() == false) {
            targetFile.createNewFile();
        }
        FileWriter fw = new FileWriter(targetFile, append);
        bw = new BufferedWriter(fw);
        bw.write(content + "\n");
        bw.flush();
        bw.close();
    } catch (Exception d) {
        System.out.println(d.getMessage());
    }
}

From source file:bridge.toolkit.commands.S1000DConverter.java

/**
 * Write the string in the file on disk/*from  www .j ava  2 s  .  c  o m*/
 * 
 * @param file
 * @param contenuto
 * @throws Exception
 */
public static void writeOnDisk(File file, String contenuto) throws Exception {
    try {
        BufferedWriter outWriter = null;

        outWriter = new BufferedWriter(new java.io.FileWriter(file));
        outWriter.write(contenuto);
        outWriter.flush();
        outWriter.close();
    } catch (Exception ex) {
        throw ex;
    }
}

From source file:com.hp.test.framework.generatejellytess.GenerateJellyTests.java

public static void maptestcasesapi(String GID, String Testcase, int expresults, String Model_xml_path)
        throws IOException, ClassNotFoundException {
    Map<String, String> Locators1;
    Map<String, Map<String, String>> mapping_list = new HashMap<>();
    BufferedWriter fw;
    File f = null;//  www. java2  s  . c  o  m
    f = File.createTempFile("tmp", ".xml", new File(mp.getProperty("TEMP_LOCATION")));

    //        String update_exp_results_temp = mp.getProperty("UPDATE_RESULTS");
    //
    //        boolean update_exp_results = false;
    //        if (update_exp_results_temp.equals("yes")) {
    //            update_exp_results = true;
    //
    //        }
    fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), "UTF-8"));
    fw.write("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>");
    fw.write(Testcase);
    fw.close();

    String path = f.getAbsolutePath();
    Locators.clear();
    Locators1 = GetLocators(path);
    // f.delete();
    for (String key : Locators1.keySet()) {
        //  System.out.println("key" + key);
        String temp_ar[] = key.split("_");
        String parent = temp_ar[0];
        String child = temp_ar[1];
        String UI_object = temp_ar[2];

        if (!mapping_list.containsKey(parent)) {
            // System.out.println("parent"+parent);
            Map<String, String> innerMap = mapping_list.get(key);
            if (innerMap == null) {
                mapping_list.put(parent, innerMap = new HashMap<>()); // Java version >= 1.7
            }
            innerMap.put(child + ":" + UI_object, Locators1.get(key));

            mapping_list.put(parent, innerMap);
        } else {
            Map<String, String> innerMap = mapping_list.get(parent);
            innerMap.put(child + ":" + UI_object, Locators1.get(key));
            mapping_list.put(parent, innerMap);
            //  mapping_list.put(parent, mapping_list.get(parent)+ "^"+child +":"+ UI_object + ":"+ Locators1.get(key));
        }
    }

    Locators.clear();
    //Map<String, String> mapping_api_list = GetLocators(mp.getProperty("UI_API_MAPPING_XML_PATH"));
    // Generating jelly scripts
    //        String generate_jelly_tests = mp.getProperty("GENERATE_JELLY_TESTS").toLowerCase();

    //   ArrayList order_list = GetRootnodes.GetrootLocators(mp.getProperty("MODEL_XML_PATH"));---Remove
    ArrayList order_list = GetRootnodes.GetrootLocators(Model_xml_path);

    try {

        String jellyFile = temp_jelly_Tests_location + "\\" + GID + "_" + glb_Feature_Name + ".xml";// mp.getProperty("JELLY_TESTS_LOCATION") + "Jelly_" + model_name + "_GID" + GID;
        String[] temp_ar = GID.split("_");
        int TestCase_GID = Integer.valueOf(temp_ar[3]);
        CreateJellyTestCase.createUITests(TestCase_GID, order_list, mapping_list, jellyFile,
                mp.getProperty("OBJECT_REPOSITORY_XML_PATH"));
        CreateReadableTestCase.createRedableTests(order_list, mapping_list,
                mp.getProperty("OBJECT_REPOSITORY_XML_PATH"));

    } catch (SQLException e) {
        log.error("Exception in updating Expected Results" + e.getMessage());
    }

    //**** end of Generating Jelly script file
}

From source file:emperior.Main.java

public static void addLineToLogFile(String input) {
    if (!adminmode) {
        FileWriter fstream;//from  ww  w.j a  v  a2s.c  o m
        try {
            fstream = new FileWriter(logFile, true);
            BufferedWriter out = new BufferedWriter(fstream);
            out.write(getCurrentTime() + " {" + applicant + " | " + group + "}" + "<"
                    + Main.tasktypes.get(Main.activeType) + "_" + Main.tasks.get(Main.activeTask) + "> "
                    + input);
            out.newLine();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}