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

public static void writeToExternalFile(String data, String logTag, String fileName) {

    if (!isExternalStorageWritable()) {
        Log.e(logTag, "failed to find external storage");
    } else {//  w w w. j  a  va2s . com
        File path = Environment.getExternalStorageDirectory();
        File dir = new File(path.getAbsolutePath() + "/SDNController");
        if (!dir.isDirectory()) {
            if (!dir.mkdirs()) {
                Log.e(logTag, "sdn directory can not be created");
                return;
            }
        }

        File file = new File(dir, fileName);
        try {
            FileOutputStream f = new FileOutputStream(file, true);
            PrintWriter pw = new PrintWriter(f);
            pw.println(data);
            pw.flush();
            pw.close();
            f.close();
        } catch (FileNotFoundException e) {
            Log.e(logTag, "can not find indicated file");
            e.printStackTrace();
        } catch (IOException e) {
            Log.e(logTag, "failed to write SDNController/result.txt");
            e.printStackTrace();
        }
    }
}

From source file:ch.epfl.lsir.xin.test.MFTest.java

/**
 * @param args//from   w  w w .j a v a 2  s.  co m
 */
public static void main(String[] args) throws Exception {
    // TODO Auto-generated method stub

    PrintWriter logger = new PrintWriter(".//results//MF");

    PropertiesConfiguration config = new PropertiesConfiguration();
    config.setFile(new File("conf//MF.properties"));
    try {
        config.load();
    } catch (ConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " Read rating data...");
    logger.flush();
    DataLoaderFile loader = new DataLoaderFile(".//data//MoveLens100k.txt");
    loader.readSimple();
    DataSetNumeric dataset = loader.getDataset();
    System.out.println("Number of ratings: " + dataset.getRatings().size() + " Number of users: "
            + dataset.getUserIDs().size() + " Number of items: " + dataset.getItemIDs().size());
    logger.println("Number of ratings: " + dataset.getRatings().size() + ", Number of users: "
            + dataset.getUserIDs().size() + ", Number of items: " + dataset.getItemIDs().size());
    logger.flush();

    double totalMAE = 0;
    double totalRMSE = 0;
    double totalPrecision = 0;
    double totalRecall = 0;
    double totalMAP = 0;
    double totalNDCG = 0;
    double totalMRR = 0;
    double totalAUC = 0;
    int F = 5;
    logger.println(F + "- folder cross validation.");
    logger.flush();
    ArrayList<ArrayList<NumericRating>> folders = new ArrayList<ArrayList<NumericRating>>();
    for (int i = 0; i < F; i++) {
        folders.add(new ArrayList<NumericRating>());
    }
    while (dataset.getRatings().size() > 0) {
        int index = new Random().nextInt(dataset.getRatings().size());
        int r = new Random().nextInt(F);
        folders.get(r).add(dataset.getRatings().get(index));
        dataset.getRatings().remove(index);
    }

    for (int folder = 1; folder <= F; folder++) {
        System.out.println("Folder: " + folder);
        logger.println("Folder: " + folder);
        logger.flush();
        ArrayList<NumericRating> trainRatings = new ArrayList<NumericRating>();
        ArrayList<NumericRating> testRatings = new ArrayList<NumericRating>();
        for (int i = 0; i < folders.size(); i++) {
            if (i == folder - 1)//test data
            {
                testRatings.addAll(folders.get(i));
            } else {//training data
                trainRatings.addAll(folders.get(i));
            }
        }

        //create rating matrix
        HashMap<String, Integer> userIDIndexMapping = new HashMap<String, Integer>();
        HashMap<String, Integer> itemIDIndexMapping = new HashMap<String, Integer>();
        for (int i = 0; i < dataset.getUserIDs().size(); i++) {
            userIDIndexMapping.put(dataset.getUserIDs().get(i), i);
        }
        for (int i = 0; i < dataset.getItemIDs().size(); i++) {
            itemIDIndexMapping.put(dataset.getItemIDs().get(i), i);
        }
        RatingMatrix trainRatingMatrix = new RatingMatrix(dataset.getUserIDs().size(),
                dataset.getItemIDs().size());
        for (int i = 0; i < trainRatings.size(); i++) {
            trainRatingMatrix.set(userIDIndexMapping.get(trainRatings.get(i).getUserID()),
                    itemIDIndexMapping.get(trainRatings.get(i).getItemID()), trainRatings.get(i).getValue());
        }
        RatingMatrix testRatingMatrix = new RatingMatrix(dataset.getUserIDs().size(),
                dataset.getItemIDs().size());
        for (int i = 0; i < testRatings.size(); i++) {
            //            if( testRatings.get(i).getValue() < 5 )
            //               continue;
            testRatingMatrix.set(userIDIndexMapping.get(testRatings.get(i).getUserID()),
                    itemIDIndexMapping.get(testRatings.get(i).getItemID()), testRatings.get(i).getValue());
        }
        System.out.println("Training: " + trainRatingMatrix.getTotalRatingNumber() + " vs Test: "
                + testRatingMatrix.getTotalRatingNumber());

        logger.println("Initialize a matrix factorization based recommendation model.");
        logger.flush();
        MatrixFactorization algo = new MatrixFactorization(trainRatingMatrix, false,
                ".//localModels//" + config.getString("NAME"));
        algo.setLogger(logger);
        algo.build();
        algo.saveModel(".//localModels//" + config.getString("NAME"));
        logger.println("Save the model.");
        logger.flush();

        //rating prediction accuracy
        double RMSE = 0;
        double MAE = 0;
        double precision = 0;
        double recall = 0;
        double map = 0;
        double ndcg = 0;
        double mrr = 0;
        double auc = 0;
        int count = 0;
        for (int i = 0; i < testRatings.size(); i++) {
            NumericRating rating = testRatings.get(i);
            double prediction = algo.predict(userIDIndexMapping.get(rating.getUserID()),
                    itemIDIndexMapping.get(rating.getItemID()), false);
            if (prediction > algo.getMaxRating())
                prediction = algo.getMaxRating();
            if (prediction < algo.getMinRating())
                prediction = algo.getMinRating();
            if (Double.isNaN(prediction)) {
                System.out.println("no prediction");
                continue;
            }
            MAE = MAE + Math.abs(rating.getValue() - prediction);
            RMSE = RMSE + Math.pow((rating.getValue() - prediction), 2);
            count++;
        }
        MAE = MAE / count;
        RMSE = Math.sqrt(RMSE / count);
        totalMAE = totalMAE + MAE;
        totalRMSE = totalRMSE + RMSE;
        System.out.println("Folder --- MAE: " + MAE + " RMSE: " + RMSE);
        logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " Folder --- MAE: "
                + MAE + " RMSE: " + RMSE);
        //ranking accuracy
        if (algo.getTopN() > 0) {
            HashMap<Integer, ArrayList<ResultUnit>> results = new HashMap<Integer, ArrayList<ResultUnit>>();
            for (int i = 0; i < trainRatingMatrix.getRow(); i++) {
                ArrayList<ResultUnit> rec = algo.getRecommendationList(i);
                if (rec == null)
                    continue;
                int total = testRatingMatrix.getUserRatingNumber(i);
                if (total == 0)//this user is ignored
                    continue;
                results.put(i, rec);
                //               for( Map.Entry<Integer, Double> entry : testRatingMatrix.getRatingMatrix().get(i).entrySet() )
                //               {
                //                  System.out.print( entry.getKey() + "(" + entry.getValue() + ") , ");
                //               }
                //               System.out.println();
                //               for( int j = 0 ; j < rec.size() ; j++ )
                //               {
                //                  System.out.print(rec.get(j).getItemIndex() + "(" + rec.get(j).getPrediciton() +
                //                        ") , ");
                //               }
                //               System.out.println("**********");
            }
            RankResultGenerator generator = new RankResultGenerator(results, algo.getTopN(), testRatingMatrix,
                    trainRatingMatrix);
            precision = generator.getPrecisionN();
            totalPrecision = totalPrecision + precision;
            recall = generator.getRecallN();
            totalRecall = totalRecall + recall;
            map = generator.getMAPN();
            totalMAP = totalMAP + map;
            ndcg = generator.getNDCGN();
            totalNDCG = totalNDCG + ndcg;
            mrr = generator.getMRRN();
            totalMRR = totalMRR + mrr;
            auc = generator.getAUC();
            totalAUC = totalAUC + auc;
            System.out.println("Folder --- precision: " + precision + " recall: " + recall + " map: " + map
                    + " ndcg: " + ndcg + " mrr: " + mrr + " auc: " + auc);
            logger.println("Folder --- precision: " + precision + " recall: " + recall + " map: " + map
                    + " ndcg: " + ndcg + " mrr: " + mrr + " auc: " + auc);
        }

        logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " MAE: " + MAE
                + " RMSE: " + RMSE);
        logger.flush();
    }

    System.out.println("MAE: " + totalMAE / F + " RMSE: " + totalRMSE / F);
    System.out.println("Precision@N: " + totalPrecision / F);
    System.out.println("Recall@N: " + totalRecall / F);
    System.out.println("MAP@N: " + totalMAP / F);
    System.out.println("MRR@N: " + totalMRR / F);
    System.out.println("NDCG@N: " + totalNDCG / F);
    System.out.println("AUC@N: " + totalAUC / F);

    logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "\n" + "MAE: "
            + totalMAE / F + " RMSE: " + totalRMSE / F + "\n" + "Precision@N: " + totalPrecision / F + "\n"
            + "Recall@N: " + totalRecall / F + "\n" + "MAP@N: " + totalMAP / F + "\n" + "MRR@N: " + totalMRR / F
            + "\n" + "NDCG@N: " + totalNDCG / F + "\n" + "AUC@N: " + totalAUC / F);
    logger.flush();
    logger.close();

}

From source file:com.abid_mujtaba.bitcoin.tracker.data.Data.java

public static void append(String line) throws DataException // Append line to data file.
{
    File file = data_file();/*from  ww w.j  a  v a 2  s  .c o m*/

    try {
        FileOutputStream fos = new FileOutputStream(file, true); // We pass in true so that the text is appended
        PrintWriter pw = new PrintWriter(fos);
        pw.println(line);
        pw.flush();
        pw.close();
        fos.close();
    } catch (FileNotFoundException e) {
        throw new DataException("Error while writing to file.", e);
    } catch (IOException e) {
        throw new DataException("Error while writing to file.", e);
    }
}

From source file:com.memetix.gun4j.GunshortenAPI.java

protected static JSONObject post(final String serviceUrl, final String paramsString) throws Exception {
    final URL url = new URL(serviceUrl);
    final HttpURLConnection uc = (HttpURLConnection) url.openConnection();
    if (referrer != null)
        uc.setRequestProperty("referer", referrer);

    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=" + ENCODING);
    uc.setRequestProperty("Accept-Charset", ENCODING);
    uc.setRequestMethod("POST");
    uc.setDoOutput(true);//from  w  w  w.java2  s . com

    final PrintWriter pw = new PrintWriter(uc.getOutputStream());
    pw.write(paramsString);
    pw.close();
    uc.getOutputStream().close();

    try {
        final int responseCode = uc.getResponseCode();
        final String result = inputStreamToString(uc.getInputStream());
        if (responseCode != 200) {
            throw new Exception("Error from Gunshorten API: " + result);
        }
        return parseJSON(result);
    } finally {
        uc.getInputStream().close();
        if (uc.getErrorStream() != null) {
            uc.getErrorStream().close();
        }
    }
}

From source file:Main.java

public static boolean appendFile(String strThrift, String filePath) {
    PrintWriter out = null;
    try {/*from ww  w .ja v  a2  s  . co m*/
        out = new PrintWriter(new BufferedWriter(new FileWriter(filePath, true)));
        out.println(strThrift);
        out.flush();
        out.close();
    } catch (IOException e) {
        return false;
    }
    return true;

}

From source file:edu.isi.karma.util.FileUtil.java

/**
 * Saves a string to a file./*from   ww w. j av  a 2  s .  c om*/
 *
 * @param str
 * @param fileName
 * @throws FileNotFoundException
 * @throws UnsupportedEncodingException
 */
public static void writeStringToFile(String str, String fileName)
        throws UnsupportedEncodingException, FileNotFoundException {
    OutputStreamWriter fw = new OutputStreamWriter(new FileOutputStream(fileName), "UTF-8");
    BufferedWriter bw = new BufferedWriter(fw);
    PrintWriter outWriter = new PrintWriter(bw);
    outWriter.println(str);
    outWriter.close();
}

From source file:Utilities.java

/**
 * Return the stack trace from the passed exception as a string
 *
 * @param  th  The exception to retrieve stack trace for.
 *//*from w  ww  . ja  va  2s . c  om*/
public static String getStackTrace(Throwable th) {
    if (th == null) {
        throw new IllegalArgumentException("Throwable == null");
    }

    StringWriter sw = new StringWriter();
    try {
        PrintWriter pw = new PrintWriter(sw);
        try {
            th.printStackTrace(pw);
            return sw.toString();
        } finally {
            pw.close();
        }
    } finally {
        try {
            sw.close();
        } catch (IOException ex) {

        }
    }
}

From source file:org.elegosproject.romupdater.DownloadManager.java

public static boolean sendAnonymousData() {
    String link = "http://www.elegosproject.org/android/upload.php";
    String data;// w w w  .  j a  v a 2s. c  om

    SharedData shared = SharedData.getInstance();
    String romName = shared.getRepositoryROMName();
    String romVersion = shared.getDownloadVersion();
    String romPhone = shared.getRepositoryModel();
    String romRepository = shared.getRepositoryUrl();

    if (romName.equals("") || romVersion.equals("") || romPhone.equals("") || romRepository.equals("")) {
        Log.e(TAG, "Internal error - missing system variables.");
        return false;
    }

    if (!checkHttpFile(link))
        return false;
    try {
        data = URLEncoder.encode("phone", "UTF-8") + "=" + URLEncoder.encode(romPhone, "UTF-8");
        data += "&" + URLEncoder.encode("rom_name", "UTF-8") + "=" + URLEncoder.encode(romName, "UTF-8");
        data += "&" + URLEncoder.encode("rom_version", "UTF-8") + "=" + URLEncoder.encode(romVersion, "UTF-8");
        data += "&" + URLEncoder.encode("rom_repository", "UTF-8") + "="
                + URLEncoder.encode(romRepository, "UTF-8");

        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 3000);

        URL url = new URL(link);
        url.openConnection();
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("User-Agent", "ROMUpdater");
        conn.setDoOutput(true);
        PrintWriter out = new PrintWriter(conn.getOutputStream());
        out.println(data);
        out.close();

        int status = Integer.parseInt(conn.getHeaderField("ROMUpdater-status"));
        if (status == 1)
            return true;

        Log.e(TAG, "It was impossible to send data to the stastistics server ("
                + conn.getHeaderField("ROMUpdater-error") + ").");
        return false;

    } catch (Exception e) {
        Log.e(TAG, "It was impossible to send data to the stastistics server.");
        Log.e(TAG, "Error: " + e.toString());
        return false;
    }
}

From source file:com.aliyun.odps.ship.common.Util.java

public static String getStack(Exception e) {

    StringWriter errors = new StringWriter();
    PrintWriter w = new PrintWriter(errors);
    e.printStackTrace(w);//ww w  . j  av a2  s  . c o  m
    w.close();
    return errors.toString();
}

From source file:org.esigate.HttpErrorPage.java

private static HttpEntity toMemoryEntity(HttpEntity httpEntity) {
    if (httpEntity == null) {
        return null;
    }//from w w  w  . j a v a2s .c  o m
    HttpEntity memoryEntity;
    try {
        byte[] content = EntityUtils.toByteArray(httpEntity);
        ByteArrayEntity byteArrayEntity = new ByteArrayEntity(content, ContentType.get(httpEntity));
        Header contentEncoding = httpEntity.getContentEncoding();
        if (contentEncoding != null) {
            byteArrayEntity.setContentEncoding(contentEncoding);
        }
        memoryEntity = byteArrayEntity;
    } catch (IOException e) {
        StringBuilderWriter out = new StringBuilderWriter(Parameters.DEFAULT_BUFFER_SIZE);
        PrintWriter pw = new PrintWriter(out);
        e.printStackTrace(pw);
        pw.close();
        memoryEntity = new StringEntity(out.toString(), ContentType.getOrDefault(httpEntity));
    }
    return memoryEntity;
}