Example usage for java.io FileWriter close

List of usage examples for java.io FileWriter close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Usage

From source file:com.bumptech.glide.disklrucache.DiskLruCacheTest.java

public static void writeFile(File file, String content) throws Exception {
    FileWriter writer = new FileWriter(file);
    writer.write(content);/*from   w  w w  .  ja  v  a2  s  . c o m*/
    writer.close();
}

From source file:funcoes.funcoes.java

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

    int dia, mes, ano;
    String data_log;/*from   w  ww.jav  a2s  . c o  m*/
    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:gov.nasa.jpl.memex.pooledtimeseries.PoT.java

private static void writeSimilarityToJSONFile(ArrayList<Path> files, double[][] similarities) {
      JSONObject root_json_obj = new JSONObject();

      for (int i = 0; i < similarities.length; i++) {
          JSONObject fileJsonObj = new JSONObject();

          for (int j = 0; j < similarities[0].length; j++) {
              fileJsonObj.put(files.get(j).getFileName(), similarities[i][j]);
          }/*from w  ww.j av a 2s.  c o  m*/

          root_json_obj.put(files.get(i).getFileName(), fileJsonObj);
      }

      try {
          outputFile = outputFile.substring(0, outputFile.lastIndexOf('.')) + ".json";
          FileWriter file = new FileWriter(outputFile);
          file.write(root_json_obj.toJSONString());
          file.flush();
          file.close();
      } catch (IOException e) {
          e.printStackTrace();
      }
  }

From source file:com.act.lcms.db.analysis.WaveformAnalysis.java

public static void printIntensityTimeGraphInCSVFormat(List<XZ> values, String fileName) throws Exception {
    FileWriter chartWriter = new FileWriter(fileName);
    chartWriter.append("Intensity, Time");
    chartWriter.append(NEW_LINE_SEPARATOR);
    for (XZ point : values) {
        chartWriter.append(point.getIntensity().toString());
        chartWriter.append(COMMA_DELIMITER);
        chartWriter.append(point.getTime().toString());
        chartWriter.append(NEW_LINE_SEPARATOR);
    }//from w  w  w.  j av a2  s.c o m
    chartWriter.flush();
    chartWriter.close();
}

From source file:com.bigtester.ate.tcg.controller.TrainingFileDB.java

/**
 * Write cache csv file.//from   www  .  j  a v a 2 s .co m
 *
 * @param absoluteCacheFilePath
 *            the absolute cache file path
 * @param beginningComments
 *            the beginning comments
 * @param endingComments
 *            the ending comments
 * @param trainedRecords
 *            the trained records
 * @param append
 *            the append
 * @throws IOException
 */
public static void writeCacheCsvFile(String absoluteCacheFilePath, String beginningComments,
        String endingComments, List<UserInputTrainingRecord> trainedRecords, boolean append)
        throws IOException {
    // Create new students objects

    FileWriter fileWriter = null;// NOPMD

    CSVPrinter csvFilePrinter = null;// NOPMD

    // Create the CSVFormat object with "\n" as a record delimiter
    CSVFormat csvFileFormat = getCSVFormat();
    try {
        if (trainedRecords.isEmpty()) {
            fileWriter = new FileWriter(absoluteCacheFilePath, append);

            // initialize CSVPrinter object
            csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);

            // Write a new student object list to the CSV file
            csvFilePrinter.printComment(beginningComments);
            csvFilePrinter.printComment(endingComments);

            fileWriter.flush();
            fileWriter.close();
            csvFilePrinter.close();
            return;
        }

        // initialize FileWriter object
        fileWriter = new FileWriter(absoluteCacheFilePath, append);

        // initialize CSVPrinter object
        csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);

        // Write a new student object list to the CSV file
        csvFilePrinter.printComment(beginningComments);
        for (UserInputTrainingRecord student : trainedRecords) {
            List<String> studentDataRecord = new ArrayList<String>();
            studentDataRecord.add(student.getInputLabelName());
            studentDataRecord.add(student.getInputMLHtmlCode());

            csvFilePrinter.printRecord(studentDataRecord);
        }
        csvFilePrinter.printComment(endingComments);
        // System.out.println("CSV file was created successfully !!!");

    } catch (Exception e) {// NOPMD
        throw new IOException("Error in CsvFileWriter !!!");// NOPMD
        // e.printStackTrace();
    } finally { //NOPMD
        try {
            if (null != fileWriter) {
                fileWriter.flush();
                fileWriter.close();
            }
            if (null != csvFilePrinter)
                csvFilePrinter.close();
        } catch (IOException e) {//NOPMD
            //System.out
            throw new IOException("Error while flushing/closing fileWriter/csvPrinter !!!");//NOPMD
            //e.printStackTrace();
        }
    }
}

From source file:com.photon.phresco.impl.IPhoneApplicationProcessor.java

public static void updateJsonInfo(JSONObject toJson, String jsonFile) throws PhrescoException {
    BufferedWriter out = null;//from  w w  w.ja v a  2s . c  o m
    FileWriter fstream = null;
    try {
        Gson gson = new Gson();
        FileWriter writer = null;
        String json = gson.toJson(toJson);
        writer = new FileWriter(jsonFile);
        writer.write(json);
        writer.flush();
    } catch (IOException e) {
        throw new PhrescoException(e);
    } finally {
        try {
            if (out != null) {
                out.close();
            }
            if (fstream != null) {
                fstream.close();
            }
        } catch (IOException e) {
            throw new PhrescoException(e);
        }
    }
}

From source file:com.ibm.research.rdf.store.runtime.service.sql.StoreHelper.java

private static void doSql(Connection conn, Backend backend, String t) {
    String generateSqlOnly = System.getProperty("com.ibm.rdf.generateStoreSQL");
    if (generateSqlOnly != null) {
        try {/*  w  ww  .  j  a  va  2 s.  c o m*/
            FileWriter fw = new FileWriter(generateSqlOnly, true);
            fw.append(t);
            fw.append(backend == Store.Backend.postgresql || backend == Store.Backend.shark ? ";\n" : "\n");
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
            assert false;
        }
    } else {
        SQLExecutor.executeUpdate(conn, t);
    }
}

From source file:fr.cls.atoll.motu.processor.wps.TestServiceMetadata.java

public static void testLoadOGCServiceMetadata() {
    // String xmlFile =
    // "J:/dev/atoll-v2/atoll-motu/atoll-motu-processor/src/test/resources/xml/TestServiceMetadata.xml";
    String xmlFile = "C:/Documents and Settings/dearith/Mes documents/Atoll/SchemaIso/TestServiceMetadataOK.xml";

    String schemaPath = "schema/iso19139";

    try {//from  w  ww .j  ava2 s .  c o  m
        List<String> errors = validateServiceMetadataFromString(xmlFile, schemaPath);
        if (errors.size() > 0) {
            StringBuffer stringBuffer = new StringBuffer();
            for (String str : errors) {
                stringBuffer.append(str);
                stringBuffer.append("\n");
            }
            throw new MotuException(String.format("ERROR - XML file '%s' is not valid - See errors below:\n%s",
                    xmlFile, stringBuffer.toString()));
        } else {
            System.out.println(String.format("XML file '%s' is valid", xmlFile));
        }

    } catch (MotuException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    InputStream in = null;
    try {
        in = Organizer.getUriAsInputStream(xmlFile);
    } catch (MotuException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    JAXBContext jc = null;
    try {
        // jc = JAXBContext.newInstance("org.isotc211.iso19139.d_2006_05_04.srv");
        // jc = JAXBContext.newInstance("org.isotc211.iso19139.d_2006_05_04.srv");
        jc = JAXBContext
                .newInstance(new Class[] { org.isotc211.iso19139.d_2006_05_04.srv.ObjectFactory.class });
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        Source srcFile = new StreamSource(xmlFile);
        JAXBElement<?> element = (JAXBElement<?>) unmarshaller.unmarshal(srcFile);
        // JAXBElement<?> element = (JAXBElement<?>) unmarshaller.unmarshal(in);
        SVServiceIdentificationType serviceIdentificationType = (SVServiceIdentificationType) element
                .getValue();
        // serviceIdentificationType = (SVServiceIdentificationType) unmarshaller.unmarshal(in);
        System.out.println(serviceIdentificationType.toString());

        List<SVOperationMetadataPropertyType> operationMetadataPropertyTypeList = serviceIdentificationType
                .getContainsOperations();

        for (SVOperationMetadataPropertyType operationMetadataPropertyType : operationMetadataPropertyTypeList) {

            SVOperationMetadataType operationMetadataType = operationMetadataPropertyType
                    .getSVOperationMetadata();
            System.out.println("---------------------------------------------");
            if (operationMetadataType == null) {
                continue;
            }
            System.out.println(operationMetadataType.getOperationName().getCharacterString().getValue());
            System.out.println(operationMetadataType.getInvocationName().getCharacterString().getValue());
            System.out.println(operationMetadataType.getOperationDescription().getCharacterString().getValue());

            CIOnlineResourcePropertyType onlineResourcePropertyType = operationMetadataType.getConnectPoint()
                    .get(0);
            if (onlineResourcePropertyType != null) {
                System.out.println(operationMetadataType.getConnectPoint().get(0).getCIOnlineResource()
                        .getLinkage().getURL());
            }

            List<SVParameterPropertyType> parameterPropertyTypeList = operationMetadataType.getParameters();

            for (SVParameterPropertyType parameterPropertyType : parameterPropertyTypeList) {
                SVParameterType parameterType = parameterPropertyType.getSVParameter();

                if (parameterType.getName().getAName().getCharacterString() != null) {
                    System.out.println(parameterType.getName().getAName().getCharacterString().getValue());
                } else {
                    System.out.println("WARNING - A parameter has no name");

                }
                if (parameterType.getDescription() != null) {
                    if (parameterType.getDescription().getCharacterString() != null) {
                        System.out.println(parameterType.getDescription().getCharacterString().getValue());
                    } else {
                        System.out.println("WARNING - A parameter has no description");

                    }
                } else {
                    System.out.println("WARNING - A parameter has no description");

                }
            }

        }
        FileWriter writer = new FileWriter("c:/tempVFS/test.xml");

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.marshal(element, writer);

        writer.flush();
        writer.close();

        System.out.println("End testLoadOGCServiceMetadata");
    } catch (JAXBException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.metawatch.manager.Monitors.java

public static JSONObject getJSONfromURL(String url) {

    //initialize//ww w .  j  av a 2s  .  c  om
    InputStream is = null;
    String result = "";
    JSONObject jArray = null;

    //http post
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

    } catch (Exception e) {
        if (Preferences.logging)
            Log.e(MetaWatch.TAG, "Error in http connection " + e.toString());
    }

    //convert response to string
    if (is != null) {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();
        } catch (Exception e) {
            if (Preferences.logging)
                Log.e(MetaWatch.TAG, "Error converting result " + e.toString());
        }

        // dump to sdcard for debugging
        File sdCard = Environment.getExternalStorageDirectory();
        File file = new File(sdCard, "weather.json");

        try {
            FileWriter writer = new FileWriter(file);
            writer.append(result);
            writer.flush();
            writer.close();
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // try parse the string to a JSON object
        try {
            jArray = new JSONObject(result);
        } catch (JSONException e) {
            if (Preferences.logging)
                Log.e(MetaWatch.TAG, "Error parsing data " + e.toString());
        }
    }
    return jArray;
}

From source file:com.ephesoft.dcma.util.XMLUtil.java

/**
 * To Output html Stream for ISO Encoding.
 * /*from w  ww  .j a v  a  2  s  . c  o m*/
 * @param pathOfHOCRFile String
 * @param outputFilePath String
 * @return FileWriter
 * @throws IOException
 */
public static void htmlOutputStreamForISOEncoding(final String pathOfHOCRFile, final String outputFilePath)
        throws IOException {

    Tidy tidy = new Tidy();
    tidy.setXHTML(true);
    tidy.setDocType(DOC_TYPE_OMIT);
    tidy.setInputEncoding(ISO_ENCODING);
    tidy.setOutputEncoding(ISO_ENCODING);
    tidy.setHideEndTags(false);

    FileInputStream inputStream = null;
    FileWriter outputStream = null;
    try {
        inputStream = new FileInputStream(pathOfHOCRFile);
        outputStream = new FileWriter(outputFilePath);
        tidy.parse(inputStream, outputStream);
    } finally {
        if (null != inputStream) {
            inputStream.close();
        }
        if (null != outputStream) {
            outputStream.flush();
            outputStream.close();
        }
    }
}