Example usage for java.io PrintWriter close

List of usage examples for java.io PrintWriter close

Introduction

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

Prototype

public void close() 

Source Link

Document

Closes the stream and releases any system resources associated with it.

Usage

From source file:it.greenvulcano.util.txt.TextUtils.java

/**
 * Writes a text String into a file// ww w. j  av a  2  s  .co  m
 * 
 * @param contentString
 *        The String to be written into the file
 * @param file
 *        The destination file
 * @param append
 *        If true the data are appended to existent file
 * @throws IOException
 */
public static void writeFile(String contentString, File file, boolean append) throws IOException {
    PrintWriter out = null;
    try {
        out = new PrintWriter(new FileWriter(file, append));
        out.print(contentString);
        out.flush();
    } finally {
        if (out != null) {
            out.close();
        }
    }
}

From source file:com.sshtools.appframework.ui.SshToolsApplication.java

public static void saveMRU(SshToolsApplication app) {
    File a = app.getApplicationPreferencesDirectory();
    if (a != null) {
        try {//from  w w w .  j a v  a 2  s  .  com
            File f = new File(app.getApplicationPreferencesDirectory(), app.getApplicationName() + ".mru");
            PrintWriter w = new PrintWriter(new OutputStreamWriter(new FileOutputStream(f), "UTF-8"), true);
            try {
                w.println(mruModel.getMRUList().toString());
            } finally {
                w.close();
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

From source file:edu.ucsd.ccdb.cil.xml2json.XML2JsonUtil.java

public void outputStringToFile(File f, String json) throws Exception {
    FileOutputStream fout = new FileOutputStream(f);
    PrintWriter pw = new PrintWriter(fout);
    pw.print(json);//from w  w  w  .j av a 2 s  . c  o m
    pw.close();
}

From source file:at.tuwien.ifs.somtoolbox.data.InputDataWriter.java

/** Writes the class information to a file in SOMLib format. */
public static void writeAsSOMLib(HashMap<String, String> classInfo, HashSet<String> classNames, String fileName)
        throws IOException, SOMLibFileFormatException {
    ArrayList<String> classNamesList = new ArrayList<String>(classNames);
    Collections.sort(classNamesList);

    PrintWriter writer = FileUtils.openFileForWriting("SOMLib class info", fileName);
    writer.println("$TYPE class_information");

    writer.println("$NUM_CLASSES " + classNames.size());
    writer.println("$CLASS_NAMES " + StringUtils.toString(classNamesList, "", "", " "));
    writer.println("$XDIM 2");
    writer.println("$YDIM " + classInfo.size());
    for (String key : classInfo.keySet()) {
        writer.println(key + " " + classNamesList.indexOf(classInfo.get(key)));
    }/*from   w w w  .  jav  a  2 s  .c  o m*/

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

From source file:it.greenvulcano.util.txt.TextUtils.java

/**
 * Writes a text String into a file/*from w ww. java2s  .  c  o m*/
 * 
 * @param contentString
 *        The StringBuffer to be written into the file
 * @param file
 *        The destination file
 * @param append
 *        If true the data are appended to existent file
 * @throws IOException
 */
@SuppressWarnings("deprecation")
public static void writeFile(StringBuffer contentString, File file, boolean append) throws IOException {
    PrintWriter out = null;
    try {
        out = new PrintWriter(new FileWriter(file, append));
        IOUtils.write(contentString, out);
        out.flush();
    } finally {
        if (out != null) {
            out.close();
        }
    }
}

From source file:com.iitb.cse.Utils.java

public static boolean startExperiment(int expId, String timeout, String logBgTraffic) {

    File file = null;// w w w.  j  a  v  a 2 s.  c o m
    File file1 = null;

    if (Constants.experimentDetailsDirectory.endsWith("/")) {
        file = new File(Constants.experimentDetailsDirectory + Constants.currentSession.getCurrentExperimentId()
                + "/" + Constants.configFile);
        file1 = new File(
                Constants.experimentDetailsDirectory + Constants.currentSession.getCurrentExperimentId());
    } else {
        file = new File(Constants.experimentDetailsDirectory + "/"
                + Constants.currentSession.getCurrentExperimentId() + "/" + Constants.configFile);
        file1 = new File(
                Constants.experimentDetailsDirectory + "/" + Constants.currentSession.getCurrentExperimentId());
    }

    if (file.exists()) {
        Charset charset = Charset.forName("UTF-8");
        String line = null;

        String[] data = new String[1000];//
        int index = 0;
        data[index] = "";
        try {
            BufferedReader reader = Files.newBufferedReader(file.toPath(), charset);
            Calendar cal = Calendar.getInstance();
            while ((line = reader.readLine()) != null) {

                System.out.println("\nLENGTH : " + line.length());

                if (line.isEmpty() || line.trim().equals("")) {
                    System.out.println("\nCASE1");
                    continue;
                } else if (line.trim().equals("*****\n")) {
                    System.out.println("\nCASE2");
                    data[index] = expId + "\n" + data[index];
                    index++;
                    data[index] = "";
                    continue;
                } else if (line.trim().equals("*****")) {
                    System.out.println("\nCASE3");
                    data[index] = expId + "\n" + data[index];
                    index++;
                    data[index] = "";
                    continue;
                }

                String[] lineVariables = line.split(" ");

                //   int offset = Integer.parseInt(lineVariables[1]);
                //   cal.add(Calendar.SECOND, offset);
                //****************************************************
                double time = Double.parseDouble(lineVariables[1]);

                int sec = (int) time;
                double rem = time % 1;
                int remainder = (int) (rem * 1000);
                //       Calendar cal = Calendar.getInstance();
                //   System.out.println("\nSec : " + sec + "\nMiSec : " + remainder + "\nTime : " + cal.getTime());
                int flag = 0;
                if (remainder < 100) {
                    flag = 1;
                    remainder = remainder + 100;
                    cal.add(Calendar.SECOND, sec);
                    cal.add(Calendar.MILLISECOND, remainder);
                    cal.add(Calendar.MILLISECOND, -100);
                } else {
                    cal.add(Calendar.SECOND, sec);
                    cal.add(Calendar.MILLISECOND, remainder);
                }

                //****************************************************
                if (lineVariables.length == 5) {
                    //       System.out.println("\nINSIDE");
                    data[index] += generateLine(cal, lineVariables[2], lineVariables[0], lineVariables[3],
                            lineVariables[4]);
                } else {
                    //    System.out.println("\nOUTSIDE");
                    data[index] += generateLine(cal, lineVariables[2], lineVariables[0], lineVariables[3]);
                }

                if (flag == 1) {
                    cal.add(Calendar.SECOND, -1 * sec);
                    cal.add(Calendar.MILLISECOND, -1 * remainder);
                    cal.add(Calendar.MILLISECOND, 100);
                } else {
                    cal.add(Calendar.SECOND, -1 * sec);
                    cal.add(Calendar.MILLISECOND, -1 * remainder);
                }

            }

            data[index] = expId + "\n" + data[index];

        } catch (IOException ex) {
            System.out.println(ex.toString());
            return false;
        }

        int controlFileIndex = 0;
        for (DeviceInfo d : Constants.currentSession.getFilteredClients()) {

            if (controlFileIndex >= Constants.currentSession.getFilteredClients().size()) {
                break;
            } else if (data[controlFileIndex] != null) {

                String jsonString = Utils.getControlFileJson(data[controlFileIndex], timeout, logBgTraffic);
                System.out.println("\njsonString : " + jsonString);
                System.out.println("\nControl FIle : " + data[controlFileIndex]);

                /* Locally keep the corresponding control file to each client*/
                PrintWriter writer;
                try {
                    writer = new PrintWriter(file1 + "/" + d.macAddress + "_confFile");
                    writer.write(data[controlFileIndex]);
                    writer.flush();
                    writer.close();
                } catch (FileNotFoundException ex) {
                    System.out.println("\nException : " + ex.toString());
                }

                //writer.close();
                System.out.println("\nDevice Info : IP " + d.ip + " Port " + d.port + " Mac " + d.macAddress);
                Thread sendData = new Thread(new SendData(expId, d, 0, jsonString, data[controlFileIndex]));
                sendData.start();
            } else {
                break;
            }
            controlFileIndex++;
        }
    } else {
        System.out.println("\nConfig FIle not found in location : " + Constants.experimentDetailsDirectory
                + Constants.currentSession.getCurrentExperimentId());
    }

    return true;
}

From source file:com.netscape.cmsutil.util.Utils.java

public static void copy(String orig, String dest) throws Exception {
    BufferedReader in = null;/*from w  w w.j av  a 2 s .com*/
    PrintWriter out = null;
    try {
        in = new BufferedReader(new FileReader(orig));
        out = new PrintWriter(new BufferedWriter(new FileWriter(dest)));
        String line = "";
        while (in.ready()) {
            line = in.readLine();
            if (line != null)
                out.println(line);
        }
    } catch (Exception ee) {
        ee.printStackTrace();
        throw ee;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (out != null) {
            out.close();
        }
    }
}

From source file:com.jolbox.benchmark.BenchmarkLaunch.java

/**
 * @param results//from   w w w  . ja  va 2s .  co  m
 * @param delay 
 * @param statementBenchmark 
 * @param noC3P0 
 * @throws IOException 
 */
private static void doPlotLineGraph(long[][] results, int delay, boolean statementBenchmark, boolean noC3P0)
        throws IOException {
    String title = "Multi-Thread test (" + delay + "ms delay)";
    if (statementBenchmark) {
        title += "\n(with PreparedStatements tests)";
    }
    String fname = System.getProperty("java.io.tmpdir") + File.separator + "bonecp-multithread-" + delay
            + "ms-delay";
    if (statementBenchmark) {
        fname += "-with-preparedstatements";
    }
    fname += "-poolsize-" + BenchmarkTests.pool_size + "-threads-" + BenchmarkTests.threads;
    if (noC3P0) {
        fname += "-noC3P0";
    }
    PrintWriter out = new PrintWriter(new FileWriter(fname + ".txt"));
    fname += ".png";

    XYSeriesCollection dataset = new XYSeriesCollection();
    for (int i = 0; i < ConnectionPoolType.values().length; i++) { //
        if (!ConnectionPoolType.values()[i].isEnabled()
                || (noC3P0 && ConnectionPoolType.values()[i].equals(ConnectionPoolType.C3P0))) {
            continue;
        }
        XYSeries series = new XYSeries(ConnectionPoolType.values()[i].toString());
        out.println(ConnectionPoolType.values()[i].toString());
        for (int j = 1 + BenchmarkTests.stepping; j < results[i].length; j += BenchmarkTests.stepping) {
            series.add(j, results[i][j]);
            out.println(j + "," + results[i][j]);
        }
        dataset.addSeries(series);
    }
    out.close();

    //         Generate the graph
    JFreeChart chart = ChartFactory.createXYLineChart(title, // Title
            "threads", // x-axis Label
            "time (ns)", // y-axis Label
            dataset, // Dataset
            PlotOrientation.VERTICAL, // Plot Orientation
            true, // Show Legend
            true, // Use tooltips
            false // Configure chart to generate URLs?
    );

    XYPlot plot = (XYPlot) chart.getPlot();
    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, false);
    plot.setRenderer(renderer);
    renderer.setSeriesPaint(0, Color.BLUE);
    renderer.setSeriesPaint(1, Color.YELLOW);
    renderer.setSeriesPaint(2, Color.BLACK);
    renderer.setSeriesPaint(3, Color.DARK_GRAY);
    renderer.setSeriesPaint(4, Color.MAGENTA);
    renderer.setSeriesPaint(5, Color.RED);
    renderer.setSeriesPaint(6, Color.LIGHT_GRAY);
    //          renderer.setSeriesShapesVisible(1, true);   
    //          renderer.setSeriesShapesVisible(2, true);   

    try {
        ChartUtilities.saveChartAsPNG(new File(fname), chart, 1024, 768);
        System.out.println("******* Saved chart to: " + fname);
    } catch (IOException e) {
        System.err.println("Problem occurred creating chart.");
    }

}

From source file:marytts.util.io.FileUtils.java

public static void writeTextFile(String[] textInRows, String textFile) {
    PrintWriter out = null;
    try {// w ww  . ja  va  2 s.com
        out = new PrintWriter(new FileWriter(textFile));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    if (out != null) {
        for (int i = 0; i < textInRows.length; i++)
            out.println(textInRows[i]);

        out.close();
    } else
        System.out.println("Error! Cannot create file: " + textFile);
}

From source file:com.headswilllol.basiclauncher.Launcher.java

public static void createExceptionLog(Exception ex, boolean gameThread) {
    Calendar cal = Calendar.getInstance();
    String minute = cal.get(Calendar.MINUTE) + "";
    minute = (minute.length() < 2 ? "0" : "") + minute;
    String second = cal.get(Calendar.SECOND) + "";
    second = (second.length() < 2 ? "0" : "") + second;
    String time = cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-"
            + cal.get(Calendar.DAY_OF_MONTH) + "_" + cal.get(Calendar.HOUR_OF_DAY) + "-" + minute + "-" + second
            + "-" + cal.get(Calendar.MILLISECOND);
    try {/*from   ww w .j a  va  2s  .co m*/
        if (!new File(appData(), FOLDER_NAME + File.separator + "errorlogs").exists())
            new File(appData(), FOLDER_NAME + File.separator + "errorlogs").mkdir();
        new File(appData(), FOLDER_NAME + File.separator + "errorlogs" + File.separator + time + ".log")
                .createNewFile();
        System.out.println("Saved error log to " + appData() + File.separator + FOLDER_NAME + File.separator
                + "errorlogs" + File.separator + time + ".log");
        PrintWriter writer = new PrintWriter(appData() + File.separator + FOLDER_NAME + File.separator
                + "errorlogs" + File.separator + time + ".log", "UTF-8");
        writer.print(getLogHeader(gameThread));
        ex.printStackTrace(writer);
        writer.print("-----------------END ERROR LOG-----------------\n");
        writer.close();
    } catch (Exception exc) {
        // Well, shit.
        exc.printStackTrace();
        Launcher.progress = "An exception occurred while saving an exception log.";
        Launcher.fail = "Errors occurred; see console for details.";
    }
}