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

public static void writeLifeLogCountInFile(int walking, int running, int vehicle, int bicycle, String filename)
        throws IOException {
    Date date = new Date();
    BufferedWriter writer = null;
    File dir = new File(Environment.getExternalStorageDirectory() + "/LifeLog");
    Log.d("Directory PATH", dir.getAbsolutePath());
    boolean flag = dir.mkdir();
    Log.d("Directory created?", "" + flag);
    File file = new File(dir.getAbsolutePath(), filename);
    if (file.exists() == false) {
        file.createNewFile();/*from  ww  w. jav a 2  s . com*/
        writer = new BufferedWriter(new FileWriter(file, true));
        writer.write("Date,Walking,Running,Bicycle,Vehicle");
        writer.newLine();
        writer.write(date.toString() + "," + walking + "," + running + "," + bicycle + "," + vehicle);
        writer.newLine();
    } else {
        writer = new BufferedWriter(new FileWriter(file, true));
        writer.write(date.toString() + "," + walking + "," + running + "," + bicycle + "," + vehicle);
        writer.newLine();
        Log.d("Appended", "True");
    }
    writer.flush();
    writer.close();

}

From source file:Main.java

public static void writeInteractionInFile(Context context, String startTime, String endTime, long duration,
        String filename) throws IOException, Exception {

    BufferedWriter writer = null;
    //String path="sdcard/LifeTracker/lifetracker.csv";
    File dir = new File("sdcard/SleepLog");
    boolean flag = dir.mkdir();
    //Log.d("Directory created?",""+flag);
    File file = new File(dir.getAbsolutePath(), filename);
    if (file.exists() == false) {
        //                  Intent service = new Intent(context,DataBaseService.class);
        //                  context.startService(service);
        file.createNewFile();// ww w .  j ava  2 s. c  om
        writer = new BufferedWriter(new FileWriter(file, true));
        writer.write("Start Time,End Time,Duration");
        writer.newLine();
        writer.write(startTime + "," + endTime + "," + duration);
    } else {
        writer = new BufferedWriter(new FileWriter(file, true));
        writer.newLine();
        writer.write(startTime + "," + endTime + "," + duration);
    }
    Log.d("Appended", "True");
    writer.flush();
    writer.close();

}

From source file:net.naijatek.myalumni.util.utilities.FileUtil.java

/**
 * Write content to_email a fileName with the destEncoding
 * //  w  ww . j ava  2s  . c o  m
 * @param content String
 * @param fileName String
 * @param destEncoding String
 * @throws FileNotFoundException
 * @throws IOException
 */
public static void writeFile(final String content, final String fileName, final String destEncoding)
        throws FileNotFoundException, IOException {

    File file = null;
    try {
        file = new File(fileName);
        if (file.isFile() == false) {
            throw new IOException("'" + fileName + "' is not a file.");
        }
        if (file.canWrite() == false) {
            throw new IOException("'" + fileName + "' is a read-only file.");
        }
    } finally {
        // we dont have to close File here
    }

    BufferedWriter out = null;
    try {
        FileOutputStream fos = new FileOutputStream(fileName);
        out = new BufferedWriter(new OutputStreamWriter(fos, destEncoding));

        out.write(content);
        out.flush();
    } catch (FileNotFoundException fe) {
        logger.error("Error", fe);
        throw fe;
    } catch (IOException e) {
        logger.error("Error", e);
        throw e;
    } finally {
        try {
            if (out != null) {
                out.close();
            }
        } catch (IOException ex) {
        }
    }
}

From source file:Messenger.TorLib.java

/**
 * This method makes a http GET request for the specified resource to the specified hostname.
 * It uses the SOCKS proxy to a connection over Tor.
 * The DNS lookup is also done over Tor.
 * This method only uses port 443 for SSL.
 *
 * @param hostname hostname for target server.
 * @param port port to connect to./*from   www. j  a v  a2  s.co m*/
 * @param resource resource to lookup with GET request.
 * @return returns a JSON object.
 * @throws IOException
 * @throws JSONException
 */
public static JSONObject getJSON(String hostname, int port, String resource)
        throws IOException, JSONException, HttpException {
    //Create a SSL socket using Tor
    Socket socket = TorSocket(hostname, port);
    SSLSocketFactory sslSf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    SSLSocket sslSocket = (SSLSocket) sslSf.createSocket(socket, null, socket.getPort(), false);
    sslSocket.setUseClientMode(true);
    sslSocket.startHandshake();
    openSockets.add(sslSocket);

    //Create the HTTP GET request and push it over the outputstream
    BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(sslSocket.getOutputStream(), "UTF8"));
    wr.write("GET /" + resource + " HTTP/1.0\r\n");
    wr.write("Host: " + hostname + "\r\n");
    wr.write("\r\n");
    wr.flush();

    //Listen for a response on the inputstream
    BufferedReader br = new BufferedReader(new InputStreamReader(sslSocket.getInputStream()));
    String t;
    boolean start = false;
    String output = "";
    while ((t = br.readLine()) != null) {
        if (t.equals("")) {
            start = true;
        }
        if (start) {
            output = output + t;
        }
    }
    br.close();
    wr.close();
    sslSocket.close();
    System.out.println(output);
    openSockets.remove(sslSocket);
    return new JSONObject(output);
}

From source file:jeplus.INSELWinTools.java

/**
 * Call INSEL executable file to run the simulation
 * @param config INSEL Configuration//from   ww  w  .  j  a v  a 2  s.com
 * @param WorkDir The working directory where the input files are stored and the output files to be generated
 * @param useReadVars Whether or not to use readvars after simulation
 * @return the result code represents the state of execution steps. >=0 means successful
 */
public static int runINSEL(INSELConfig config, String WorkDir, String modelfile) {

    int ExitValue = -99;

    try {
        // Trace simulation time
        Date start = new Date();

        // Run EnergyPlus executable
        String CmdLine = config.getResolvedInselEXEC() + " " + modelfile;
        Process EPProc = Runtime.getRuntime().exec(CmdLine, null, new File(WorkDir));

        BufferedReader ins = new BufferedReader(new InputStreamReader(EPProc.getInputStream()));
        // Use console output as the report file
        BufferedWriter outs = new BufferedWriter(new FileWriter(WorkDir + config.ScreenFile, false));
        outs.newLine();
        outs.write("Calling insel.exe - " + (new SimpleDateFormat()).format(start));
        outs.newLine();
        outs.write("Command line: " + WorkDir + ">" + CmdLine);
        outs.newLine();

        int res = ins.read();
        while (res != -1) {
            outs.write(res);
            res = ins.read();
        }
        ins.close();
        outs.newLine();
        outs.write("Simulation time: " + Long.toString((new Date().getTime() - start.getTime()) / 1000)
                + " seconds");
        outs.flush();
        outs.close();

        EPProc.waitFor();
        ExitValue = EPProc.exitValue();
    } catch (IOException | InterruptedException e) {
        logger.error("Exception during INSEL execution.", e);
    }

    // Return Radiance exit value
    return ExitValue;
}

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

/** convert file content to a string array with each line separated.
 * @param strings The lines to copy to the file
 * @param file The File to read//from   ww  w . j a v  a2  s.  co  m
 */
public static void stringArrayToFile(final List<String> strings, final File file) {

    DataOutputStream out = null;
    BufferedWriter br = null;

    try {
        out = new DataOutputStream(new FileOutputStream(file));
        br = new BufferedWriter(new OutputStreamWriter(out, TactFileUtils.DEFAULT_ENCODING));

        for (final String string : strings) {
            br.write(string);
            br.write('\n');
        }
    } catch (final IOException e) {
        throw new RuntimeException("IO problem in fileToString", e);
    } finally {
        try {
            if (br != null) {
                br.close();
            }
            if (out != null) {
                out.close();
            }
        } catch (final IOException e) {
            ConsoleUtils.displayError(e);
        }
    }
}

From source file:it.tizianofagni.sparkboost.DataUtils.java

/**
 * Generate a new LibSvm output file giving each document an index corresponding to the index tha documents had on
 * original input LibSvm file.// w ww . j av  a  2  s . com
 *
 * @param sc         The spark context.
 * @param dataFile   The data file.
 * @param outputFile The output file.
 */
public static void generateLibSvmFileWithIDs(JavaSparkContext sc, String dataFile, String outputFile) {
    if (sc == null)
        throw new NullPointerException("The Spark Context is 'null'");
    if (dataFile == null || dataFile.isEmpty())
        throw new IllegalArgumentException("The dataFile is 'null'");

    ArrayList<MultilabelPoint> points = new ArrayList<>();
    try {
        Path pt = new Path(dataFile);
        FileSystem fs = FileSystem.get(pt.toUri(), new Configuration());
        BufferedReader br = new BufferedReader(new InputStreamReader(fs.open(pt)));

        Path ptOut = new Path(outputFile);
        BufferedWriter bw = new BufferedWriter((new OutputStreamWriter(fs.create(ptOut))));

        try {
            int docID = 0;
            String line = br.readLine();
            while (line != null) {
                bw.write("" + docID + "\t" + line + "\n");
                line = br.readLine();
                docID++;
            }
        } finally {
            br.close();
            bw.close();
        }
    } catch (Exception e) {
        throw new RuntimeException("Reading input LibSVM data file", e);
    }

}

From source file:at.tugraz.sss.serv.SSFileU.java

public static void appendTextToFile(String filePath, String text) throws Exception {

    FileWriter fileWriter = null;
    BufferedWriter bufferWritter = null;

    try {/*from   w  ww.j  ava  2  s. c  om*/
        fileWriter = new FileWriter(filePath, true);
        bufferWritter = new BufferedWriter(fileWriter);

        bufferWritter.write(text);

    } catch (IOException error) {
        throw error;
    } finally {

        if (bufferWritter != null) {
            bufferWritter.close();
        }

        if (fileWriter != null) {
            fileWriter.close();
        }
    }
}

From source file:net.librec.util.FileUtil.java

/**
 * Write a string into a file with the given path and content.
 *
 * @param filePath path of the file/*w  w  w .j a  v a2  s  .  c  o m*/
 * @param content  content to write
 * @param append   whether append
 * @throws Exception if error occurs
 */
public static void writeString(String filePath, String content, boolean append) throws Exception {
    String dirPath = filePath.substring(0, filePath.lastIndexOf("/") + 1);
    File dir = new File(dirPath);
    if (!dir.exists()) {
        dir.mkdirs();
    }
    BufferedWriter bw = new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream(filePath, append), "UTF-8"));
    if (content.endsWith("\n"))
        bw.write(content);
    else
        bw.write(content + "\n");
    bw.close();
}

From source file:com.ibm.bi.dml.runtime.util.MapReduceTool.java

public static void writeDimsFile(String filename, byte[] unknownFlags, long[] maxRows, long[] maxCols)
        throws IOException {
    BufferedWriter br = setupOutputFile(filename);
    StringBuilder line = new StringBuilder();
    for (int i = 0; i < unknownFlags.length; i++) {
        if (unknownFlags[i] != (byte) 0) {
            line.append(i);//from  w  ww. j  ava 2s.  c  om
            line.append(" " + maxRows[i]);
            line.append(" " + maxCols[i]);
            line.append("\n");
        }
    }
    br.write(line.toString());
    br.close();
    //System.out.println("Finished writing dimsFile: " + filename);
}