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

/**
 * Save the contents of a table to a TSV file
 * Note:  uses toString() on the header cells as well as the data cells.  If you've got funny columns,
 * expect funny behavior//from ww  w.j  a  v a  2s.com
 * @param table
 * @param outFile
 * @throws IOException
 */
public static void SaveTableAsTSV(JTable table, File outFile) throws IOException {
    PrintWriter outPW = new PrintWriter(outFile);

    TableModel tableModel = table.getModel();
    TableColumnModel columnModel = table.getColumnModel();

    StringBuffer headerLineBuf = new StringBuffer();
    for (int i = 0; i < columnModel.getColumnCount(); i++) {
        if (i > 0)
            headerLineBuf.append("\t");
        headerLineBuf.append(columnModel.getColumn(i).getHeaderValue().toString());
    }
    outPW.println(headerLineBuf.toString());
    outPW.flush();
    for (int i = 0; i < tableModel.getRowCount(); i++) {
        StringBuffer lineBuf = new StringBuffer();
        for (int j = 0; j < tableModel.getColumnCount(); j++) {
            if (j > 0)
                lineBuf.append("\t");
            lineBuf.append(tableModel.getValueAt(i, j).toString());
        }
        outPW.println(lineBuf.toString());
        outPW.flush();
    }
    outPW.close();
}

From source file:com.zimbra.kabuki.tools.img.ImageMerger.java

private static void close(PrintWriter out) {
    try {/*from  w w  w .j a v a2s. com*/
        out.close();
    } catch (Exception e) {
        /* ignore */ }
}

From source file:edu.polyu.screamalert.SoundProcessing.java

private static void saveScoreToTextFile(String eventID, String logFilename, double score, double duration,
        String decision) {/*w w  w . j a  v a  2s  .c o m*/
    String filepath = Environment.getExternalStorageDirectory().getPath();
    File file = new File(filepath, Config.AUDIO_RECORDER_FOLDER);
    if (!file.exists()) {
        file.mkdirs();
    }
    String fullname = file.getAbsolutePath() + "/" + logFilename;
    try {
        PrintWriter pw = new PrintWriter(new FileWriter(fullname, true));
        String dec = (decision.equals("Scream") ? "S" : "NS");
        pw.printf("%s,%.2f,%.3f,%s\n", eventID, duration, score, dec);
        pw.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:isl.FIMS.utils.Utils.java

private static long getFreeSpaceOnWindows(String path) throws Exception {
    long bytesFree = -1;

    File script = new File(System.getProperty("java.io.tmpdir"), //$NON-NLS-1$
            "script.bat"); //$NON-NLS-1$
    PrintWriter writer = new PrintWriter(new FileWriter(script, false));
    writer.println("dir \"" + path + "\""); //$NON-NLS-1$ //$NON-NLS-2$
    writer.close();

    // get the output from running the .bat file
    Process p = Runtime.getRuntime().exec(script.getAbsolutePath());
    InputStream reader = new BufferedInputStream(p.getInputStream());
    StringBuffer buffer = new StringBuffer();
    for (;;) {//from  w  w w  .java 2s  .  c  o m
        int c = reader.read();
        if (c == -1) {
            break;
        }
        buffer.append((char) c);
    }
    String outputText = buffer.toString();
    reader.close();

    StringTokenizer tokenizer = new StringTokenizer(outputText, "\n"); //$NON-NLS-1$
    String line = null;
    while (tokenizer.hasMoreTokens()) {
        line = tokenizer.nextToken().trim();
        // see if line contains the bytes free information

    }
    tokenizer = new StringTokenizer(line, " "); //$NON-NLS-1$
    tokenizer.nextToken();
    tokenizer.nextToken();
    bytesFree = Long.parseLong(tokenizer.nextToken().replace('.', ',').replaceAll(",", "")); //$NON-NLS-1$//$NON-NLS-2$
    return bytesFree;
}

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

/**
 * Writes the class information as <a href="http://databionic-esom.sourceforge.net/user.html#File_formats">ESOM
 * cls</a> file./*from w w  w .ja v  a2  s .  c  o m*/
 */
public static void writeAsESOM(SOMLibClassInformation classInfo, String fileName)
        throws IOException, SOMLibFileFormatException {
    PrintWriter writer = FileUtils.openFileForWriting("ESOM class info", fileName);
    writer.println("% " + classInfo.numData);
    // write class index => class name mapping in header
    for (int i = 0; i < classInfo.numClasses(); i++) {
        writer.println("% " + i + " " + classInfo.getClassName(i));
    }
    for (String element : classInfo.getDataNames()) {
        writer.println(element + "\t" + classInfo.getClassIndexForInput(element));
    }
    writer.flush();
    writer.close();
}

From source file:airlift.util.AirliftUtil.java

/**
 * Serialize stack trace./*from   w  ww  . j  a  v  a 2s .  c  o m*/
 *
 * @param _t the _t
 * @return the string
 */
public static String serializeStackTrace(Throwable _t) {
    java.io.ByteArrayOutputStream byteArrayOutputStream = new java.io.ByteArrayOutputStream();
    java.io.PrintWriter printWriter = null;
    String errorString = null;

    try {
        printWriter = new java.io.PrintWriter(byteArrayOutputStream, true);
        _t.printStackTrace(printWriter);
        errorString = byteArrayOutputStream.toString();
    } catch (Throwable u) {
        if (printWriter != null) {
            try {
                printWriter.close();
            } catch (Throwable v) {
            }
        }
    }

    return errorString;
}

From source file:com.oculusinfo.ml.spark.unsupervised.TestDPMeans.java

public static void genTestData(int k) {
    PrintWriter writer;
    try {//  w w w  .  ja v a 2 s.  c om
        writer = new PrintWriter("test.txt", "UTF-8");

        // each class size is equal 
        int classSize = 1000000 / k;

        double stdDev = 30.0;

        // generate k classes of data points using a normal distribution with random means and fixed std deviation
        for (int i = 0; i < k; i++) {
            Random rnd = new Random();

            double meanLat = rnd.nextDouble() * 400.0;
            double meanLon = rnd.nextDouble() * 400.0;

            // randomly generate a dataset of lat, lon points
            for (int j = 0; j < classSize; j++) {
                double x = rnd.nextGaussian() * stdDev + meanLat;
                double y = rnd.nextGaussian() * stdDev + meanLon;

                writer.println(x + "," + y);
            }
        }
        writer.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:it.geosolutions.geobatch.imagemosaic.ImageMosaicProperties.java

/**
 * If the regex file do not exists, build it using the passed configuration and return the
 * corresponding properties object//from  w w w.  jav a 2  s.  co m
 * 
 * @param regexFile
 * @param configuration
 * @return
 * @throws NullPointerException
 * @throws IOException 
 */
private static Properties createRegexFile(File regexFile, String regex)
        throws NullPointerException, IOException {

    if (!regexFile.exists()) {
        FileWriter outFile = null;
        PrintWriter out = null;
        if (regex != null) {
            try {
                outFile = new FileWriter(regexFile);
                out = new PrintWriter(outFile);

                // Write text to file
                out.println("regex=" + regex);
            } catch (IOException e) {
                if (LOGGER.isErrorEnabled())
                    LOGGER.error("Error occurred while writing " + regexFile.getAbsolutePath() + " file!", e);
            } finally {
                if (out != null) {
                    out.flush();
                    out.close();
                }

                outFile = null;
                out = null;
            }
        } else
            throw new NullPointerException("Unable to build the property file using a null regex string");

        return getPropertyFile(regexFile);
    }
    return null;
}

From source file:com.oculusinfo.ml.spark.unsupervised.TestKMeans.java

public static void genTestData(int k) {
    PrintWriter writer;
    try {//from   w  w w. j  a  va  2 s  .com
        writer = new PrintWriter("test.txt", "UTF-8");

        // each class size is equal 
        int classSize = 1000000 / k;

        double stdDev = 30.0;

        // generate k classes of data points using a normal distribution with random means and fixed std deviation
        for (int i = 0; i < k; i++) {
            Random rnd = new Random();

            double meanX = rnd.nextDouble() * 400.0;
            double meanY = rnd.nextDouble() * 400.0;

            // randomly generate a dataset of x, y points
            for (int j = 0; j < classSize; j++) {
                double x = rnd.nextGaussian() * stdDev + meanX;
                double y = rnd.nextGaussian() * stdDev + meanY;

                writer.println(x + "," + y);
            }
        }
        writer.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.dien.upload.server.UploadServlet.java

/**
 * Writes a XML response to the client. 
 * The message must be a text which will be wrapped in an XML structure.
 * //from w w w  .j  ava 2 s .c  om
 * Note: if the request is a POST, the response should set the content type 
 *  to text/html or text/plain in order to be able in the client side to
 *  read the iframe body (submitCompletEvent.getResults()), otherwise the
 *  method returns null 
 * 
 * @param request
 * @param response
 * @param message
 * @param post
 *        specify whether the request is post or not.   
 * @throws IOException
 */
protected static void renderXmlResponse(HttpServletRequest request, HttpServletResponse response,
        String message, boolean post) throws IOException {

    //json????

    response.setContentType("text/html;charset=utf-8");
    PrintWriter out;
    try {
        out = response.getWriter();
        out.write("<html><body><textarea>" + message + "</textarea></body></html>");
        out.flush();
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}