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:Main.java

public static boolean writeFile(String filePath, String fileName, String content, boolean append) {
    FileWriter fileWriter = null;
    boolean result = false;
    if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
        try {//from w  w  w  .  j  a va 2s  . co  m

            File file = new File(filePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            Log.i("file", filePath);
            fileWriter = new FileWriter(filePath + fileName, append);
            fileWriter.write(content);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
            Log.i("file", e.toString());
        } finally {
            if (fileWriter != null) {
                try {
                    fileWriter.close();
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        }
    }
    return result;
}

From source file:doc.doclets.WorkbenchHelpDoclet.java

private static void _writeAttrDoc(final String className, final String documentation) throws IOException {
    String fileBaseName = className + "_attributes.html";

    String fileName = null;//from  w ww  . j  a v  a 2  s.  com
    if (_outputDirectory != null) {
        fileName = _outputDirectory + File.separator + "html" + File.separator + fileBaseName;
    } else {
        fileName = fileBaseName;
    }
    // If necessary, create the directory.
    final File directoryFile = new File(fileName).getParentFile();
    if (!directoryFile.exists()) {
        if (!directoryFile.mkdirs()) {
            throw new IOException("Directory \"" + directoryFile + "\" does not exist and cannot be created.");
        }
    }
    System.out.println("Creating " + fileName);

    final FileWriter writer = new FileWriter(fileName);
    try {
        writer.write(documentation);
    } finally {
        writer.close();
    }
}

From source file:biomine.bmvis2.pipeline.GraphOperationSerializer.java

public static void saveList(Collection<GraphOperation> ops, File f, Map<String, Double> queryNodes)
        throws IOException {
    FileWriter wr = new FileWriter(f);
    JSONArray arr = new JSONArray();
    for (GraphOperation op : ops) {
        JSONObject obj = op.toJSON();//from w w  w. j  a  v  a  2s. c  om
        JSONObject mark = new JSONObject();
        mark.put("class", op.getClass().getName());
        mark.put("object", obj);
        arr.add(mark);
    }

    JSONArray noi = new JSONArray();
    for (String z : queryNodes.keySet()) {
        JSONObject jo = new JSONObject();
        jo.put("node", z);
        Double val = queryNodes.get(z);
        jo.put("value", val);
        noi.add(jo);
    }
    arr.add(noi);

    arr.writeJSONString(wr);
    wr.close();
}

From source file:cn.org.citycloud.srdz.utils.FileUtils.java

/**
 * /*from  ww w . j a  va 2s. c  o m*/
 * @param content
 * @param filePath
 */
public static void writeFile(String content, String filePath) {
    try {
        if (FileUtils.createFile(filePath)) {
            FileWriter fileWriter = new FileWriter(filePath, true);
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
            bufferedWriter.write(content);
            bufferedWriter.close();
            fileWriter.close();
        } else {
            log.info("??");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.egt.core.util.VelocityEngineer.java

public static void write(VelocityContext context, String tempname, String filename) throws Exception {
    Bitacora.trace(VelocityEngineer.class, "write", context, tempname, filename);
    StringWriter sw = write(context, tempname);
    if (sw != null) {
        FileWriter fileWriter = null;
        BufferedWriter bufferedWriter = null;
        try {/*from   ww w.j a v a2  s  .  com*/
            fileWriter = new FileWriter(filename);
            bufferedWriter = new BufferedWriter(fileWriter);
            bufferedWriter.write(sw.toString());
        } catch (IOException ex) {
            throw ex;
        } finally {
            if (bufferedWriter != null) {
                try {
                    bufferedWriter.close();
                } catch (IOException ex) {
                    Bitacora.logFatal(ex);
                }
            }
            if (fileWriter != null) {
                try {
                    fileWriter.close();
                } catch (IOException ex) {
                    Bitacora.logFatal(ex);
                }
            }
        }
    }
}

From source file:doc.doclets.WorkbenchHelpDoclet.java

/**
 * Write the output to a file./*  w w w.j  ava  2s . com*/
 * 
 * @param className The dot separated fully qualified classname, which is used to specify the directory and filename to which the documentation is written.
 * @param documentation The documentation that is written.
 * @exception IOException If there is a problem writing the documentation.
 */
private static void _writeDoc(final String className, final String documentation) throws IOException {
    String fileBaseName = className + ".html";

    String fileName = null;
    if (_outputDirectory != null) {
        fileName = _outputDirectory + File.separator + "html" + File.separator + fileBaseName;
    } else {
        fileName = fileBaseName;
    }
    // If necessary, create the directory.
    final File directoryFile = new File(fileName).getParentFile();
    if (!directoryFile.exists()) {
        if (!directoryFile.mkdirs()) {
            throw new IOException("Directory \"" + directoryFile + "\" does not exist and cannot be created.");
        }
    }
    System.out.println("Creating " + fileName);

    final FileWriter writer = new FileWriter(fileName);
    try {
        writer.write(documentation);
    } finally {
        writer.close();
    }
}

From source file:com.linkedin.pinot.perf.ForwardIndexReaderBenchmark.java

public static void multiValuedReadBenchMarkV1(File file, int numDocs, int totalNumValues, int maxEntriesPerDoc,
        int columnSizeInBits) throws Exception {
    System.out.println("******************************************************************");
    System.out.println("Analyzing " + file.getName() + " numDocs:" + numDocs + ", totalNumValues:"
            + totalNumValues + ", maxEntriesPerDoc:" + maxEntriesPerDoc + ", numBits:" + columnSizeInBits);
    long start, end;
    boolean readFile = true;
    boolean randomRead = true;
    boolean contextualRead = true;
    boolean signed = false;
    boolean isMmap = false;
    PinotDataBuffer heapBuffer = PinotDataBuffer.fromFile(file, ReadMode.mmap, FileChannel.MapMode.READ_ONLY,
            "benchmarking");
    BaseSingleColumnMultiValueReader reader = new com.linkedin.pinot.core.io.reader.impl.v1.FixedBitMultiValueReader(
            heapBuffer, numDocs, totalNumValues, columnSizeInBits, signed);

    int[] intArray = new int[maxEntriesPerDoc];
    File outfile = new File("/tmp/" + file.getName() + ".raw");
    FileWriter fw = new FileWriter(outfile);
    for (int i = 0; i < numDocs; i++) {
        int length = reader.getIntArray(i, intArray);
        StringBuilder sb = new StringBuilder();
        String delim = "";
        for (int j = 0; j < length; j++) {
            sb.append(delim);// w ww  .  j a v a 2s. c om
            sb.append(intArray[j]);
            delim = ",";
        }
        fw.write(sb.toString());
        fw.write("\n");
    }
    fw.close();

    // sequential read
    if (readFile) {
        DescriptiveStatistics stats = new DescriptiveStatistics();
        RandomAccessFile raf = new RandomAccessFile(file, "rw");
        ByteBuffer buffer = ByteBuffer.allocateDirect((int) file.length());
        raf.getChannel().read(buffer);
        for (int run = 0; run < MAX_RUNS; run++) {
            long length = file.length();
            start = System.currentTimeMillis();
            for (int i = 0; i < length; i++) {
                byte b = buffer.get(i);
            }
            end = System.currentTimeMillis();
            stats.addValue((end - start));
        }
        System.out.println("v1 multi value read bytes stats for " + file.getName());
        System.out.println(
                stats.toString().replaceAll("\n", ", ") + " raw:" + Arrays.toString(stats.getValues()));

        raf.close();
    }
    if (randomRead) {
        DescriptiveStatistics stats = new DescriptiveStatistics();
        for (int run = 0; run < MAX_RUNS; run++) {
            start = System.currentTimeMillis();
            for (int i = 0; i < numDocs; i++) {
                int length = reader.getIntArray(i, intArray);
            }
            end = System.currentTimeMillis();
            stats.addValue((end - start));
        }
        System.out.println("v1 multi value sequential read one stats for " + file.getName());
        System.out.println(
                stats.toString().replaceAll("\n", ", ") + " raw:" + Arrays.toString(stats.getValues()));
    }

    if (contextualRead) {
        DescriptiveStatistics stats = new DescriptiveStatistics();
        for (int run = 0; run < MAX_RUNS; run++) {
            MultiValueReaderContext context = (MultiValueReaderContext) reader.createContext();
            start = System.currentTimeMillis();
            for (int i = 0; i < numDocs; i++) {
                int length = reader.getIntArray(i, intArray, context);
            }
            end = System.currentTimeMillis();
            // System.out.println("RUN:" + run + "Time:" + (end-start));
            stats.addValue((end - start));
        }
        System.out.println("v1 multi value sequential read one with context stats for " + file.getName());
        System.out.println(
                stats.toString().replaceAll("\n", ", ") + " raw:" + Arrays.toString(stats.getValues()));

    }
    reader.close();
    heapBuffer.close();
    System.out.println("******************************************************************");

}

From source file:org.shareok.data.datahandlers.DataHandlersUtil.java

public static void writeCsvData(String csvFilePath, List<List<String>> data) {
    FileWriter writer = null;
    try {//from   w  w  w .ja v a  2s. c om
        String extension = DocumentProcessorUtil.getFileExtension(csvFilePath);
        CsvHandler handler = (CsvHandler) FileHandlerFactory.getFileHandlerByFileExtension(extension);
        writer = new FileWriter(csvFilePath);
        for (List<String> row : data) {
            handler.writeCsvLine(writer, row);
        }
    } catch (IOException ex) {
        logger.error("Cannot write data into csv file at " + csvFilePath, ex);
    } finally {
        try {
            writer.close();
        } catch (IOException ex) {
            logger.error("Cannot close the file write for csv file at " + csvFilePath, ex);
        }
    }
}

From source file:org.owasp.proxy.Main.java

private static SSLContextSelector getServerSSLContextSelector() throws GeneralSecurityException, IOException {
    File ks = new File("ca.p12");
    String type = "PKCS12";
    char[] password = "password".toCharArray();
    String alias = "CA";
    if (ks.exists()) {
        try {//w  w  w . j  a  va2  s  . c  om
            return new AutoGeneratingContextSelector(ks, type, password, password, alias);
        } catch (GeneralSecurityException e) {
            System.err.println("Error loading CA keys from keystore: " + e.getLocalizedMessage());
        } catch (IOException e) {
            System.err.println("Error loading CA keys from keystore: " + e.getLocalizedMessage());
        }
    }
    System.err.println("Generating a new CA");
    X500Principal ca = new X500Principal(
            "cn=OWASP Custom CA for " + java.net.InetAddress.getLocalHost().getHostName()
                    + ",ou=OWASP Custom CA,o=OWASP,l=OWASP,st=OWASP,c=OWASP");
    AutoGeneratingContextSelector ssl = new AutoGeneratingContextSelector(ca);
    try {
        ssl.save(ks, type, password, password, alias);
    } catch (GeneralSecurityException e) {
        System.err.println("Error saving CA keys to keystore: " + e.getLocalizedMessage());
    } catch (IOException e) {
        System.err.println("Error saving CA keys to keystore: " + e.getLocalizedMessage());
    }
    FileWriter pem = null;
    try {
        pem = new FileWriter("ca.pem");
        pem.write(ssl.getCACert());
    } catch (IOException e) {
        System.err.println("Error writing CA cert : " + e.getLocalizedMessage());
    } finally {
        if (pem != null)
            pem.close();
    }
    return ssl;
}

From source file:Main.java

/**
 * Print out the spike trains so it can be analyzed by plotting software
 * @param file//from  w  w  w.  j ava  2 s  .c om
 * @param array
 */
public static void printArray(File file, double[] x, double[] y) {
    FileWriter fstream = null;
    BufferedWriter out = null;

    try {
        fstream = new FileWriter(file);
        out = new BufferedWriter(fstream);
        for (int i = 0; i < x.length; i++) {
            out.write(x[i] + "\t");
        }
        out.write("\r\n");
        for (int i = 0; i < y.length; i++) {
            out.write(y[i] + "\t");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {

        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (fstream != null) {
            try {
                fstream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}