List of usage examples for java.io PrintWriter close
public void close()
From source file:PrintWriterDemo.java
public static void main() throws Exception { PrintWriter pw = new PrintWriter(new FileWriter("dice.txt")); for (int i = 1; i <= 1000; i++) { int die = (int) (1 + 6 * Math.random()); pw.print(die);//from w ww . j a va2s .c o m pw.print(' '); if (i % 20 == 0) pw.println(); } pw.println(); pw.close(); // Without this, the output file may be empty }
From source file:com.justgiving.raven.kissmetrics.utils.KissmetricsLocalSchemaExtractor.java
/**** * This function parses all the json record files in a folder and returns a counts of the total occurrences of keys * in all files//from ww w .j a v a 2s .co m * * @param inputFolder * @param outputFolder * @throws IOException */ private static void countKeysInJsonRecordsFolder(String inputFolder, String outputFile) throws IOException { File folder = new File(inputFolder); File[] listOfFiles = folder.listFiles(); KeyValueCounter totalKeyValueCounter = new KeyValueCounter(); KeyValueCounter currentKeyValueCounter = new KeyValueCounter(); for (File currentFile : listOfFiles) { if (currentFile.isFile()) { logger.info("Processing file: " + currentFile.getName()); currentKeyValueCounter = countKeysInJsonRecordsFile( Paths.get(inputFolder, currentFile.getName()).toString()); totalKeyValueCounter = deepMergeKeyValueCounter(totalKeyValueCounter, currentKeyValueCounter); } else if (currentFile.isDirectory()) { logger.warn("Sub-directory folders are currently ignored"); } } //System.out.println(totalKeyCounter.toString()); logger.info("---------------"); logger.info(sortOutputByKey(totalKeyValueCounter)); logger.info("saving output to file: "); File outpuFile = new File(outputFile); outpuFile.getParentFile().mkdirs(); PrintWriter out = new PrintWriter(outputFile); out.print(sortOutputByKey(totalKeyValueCounter)); out.close(); }
From source file:com.progressiveaccess.cmlspeech.base.FileHandler.java
/** * Writes a document to a CML file.// w ww. j ava2 s . c om * * @param doc * The output document. * @param fileName * The base filename. * @param extension * The additional extension. * * @throws IOException * Problems with opening output file. * @throws CDKException * Problems with writing the CML XOM. */ public static void writeFile(final Document doc, final String fileName, final String extension) throws IOException, CDKException { final String basename = FilenameUtils.getBaseName(fileName); final OutputStream outFile = new BufferedOutputStream( new FileOutputStream(basename + "-" + extension + ".cml")); final PrintWriter output = new PrintWriter(outFile); output.write(XOMUtil.toPrettyXML(doc)); output.flush(); output.close(); }
From source file:io.proleap.vb6.TestGenerator.java
public static void generateTreeFile(final File vb6InputFile, final File outputDirectory) throws IOException { final File outputFile = new File(outputDirectory + "/" + vb6InputFile.getName() + TREE_EXTENSION); final boolean createdNewFile = outputFile.createNewFile(); if (createdNewFile) { LOG.info("Creating tree file {}.", outputFile); final InputStream inputStream = new FileInputStream(vb6InputFile); final VisualBasic6Lexer lexer = new VisualBasic6Lexer(new ANTLRInputStream(inputStream)); final CommonTokenStream tokens = new CommonTokenStream(lexer); final VisualBasic6Parser parser = new VisualBasic6Parser(tokens); final StartRuleContext startRule = parser.startRule(); final String inputFileTree = TreeUtils.toStringTree(startRule, parser); final PrintWriter pWriter = new PrintWriter(new FileWriter(outputFile)); pWriter.write(inputFileTree);/* w w w. jav a 2 s . c o m*/ pWriter.flush(); pWriter.close(); } }
From source file:ISMAGS.CommandLineInterface.java
private static void printMotifs(Set<MotifInstance> motifs, String output) throws IOException { PrintWriter out = new PrintWriter(new File(output)); for (MotifInstance m : motifs) { out.println(m);//from w w w. j a va 2s. c o m } out.close(); }
From source file:gov.nist.appvet.tool.sigverifier.util.ReportUtil.java
/** * This method returns report information to the AppVet ToolAdapter as ASCII * text and cannot attach a file to the response. *///from w w w.ja v a 2 s. c o m public static boolean sendInHttpResponse(HttpServletResponse response, String reportText, ToolStatus reportStatus) { try { response.setStatus(HttpServletResponse.SC_OK); // HTTP 200 response.setContentType("text/html"); response.setHeader("toolrisk", reportStatus.name()); PrintWriter out = response.getWriter(); out.println(reportText); out.flush(); out.close(); log.debug("Returned report"); return true; } catch (IOException e) { log.error(e.toString()); return false; } }
From source file:GoogleAPI.java
/** * Forms an HTTP request, sends it using POST method and returns the result of the request as a JSONObject. * /* w ww .ja v a 2 s . c o m*/ * @param url The URL to query for a JSONObject. * @param parameters Additional POST parameters * @return The translated String. * @throws Exception on error. */ protected static JSONObject retrieveJSON(final URL url, final String parameters) throws Exception { try { final HttpURLConnection uc = (HttpURLConnection) url.openConnection(); uc.setRequestProperty("referer", referrer); uc.setRequestMethod("POST"); uc.setDoOutput(true); final PrintWriter pw = new PrintWriter(uc.getOutputStream()); pw.write(parameters); pw.close(); uc.getOutputStream().close(); try { final String result = inputStreamToString(uc.getInputStream()); return new JSONObject(result); } finally { // http://java.sun.com/j2se/1.5.0/docs/guide/net/http-keepalive.html if (uc.getInputStream() != null) { uc.getInputStream().close(); } if (uc.getErrorStream() != null) { uc.getErrorStream().close(); } if (pw != null) { pw.close(); } } } catch (Exception ex) { throw new Exception("[google-api-translate-java] Error retrieving translation.", ex); } }
From source file:com.google.enterprise.connector.importexport.ImportExport.java
/** * Writes a list of connectors to an XML file. * * @param connectors an ImportExportConnectorList * @param filename destination XML file for connectors. *//*from ww w .j a v a 2 s . c o m*/ public static void writeToFile(String filename, ImportExportConnectorList connectors) throws IOException { PrintWriter out = new PrintWriter(new OutputStreamWriter(new FileOutputStream(filename), "UTF-8")); connectors.toXml(out, 0); out.close(); }
From source file:StringUtils.java
/** * Convert an exception to a String with full stack trace * @param ex the exception//from www.j a v a2 s.c o m * @return a String with the full stacktrace error text */ public static String getStringFromStackTrace(Throwable ex) { if (ex == null) { return ""; } StringWriter str = new StringWriter(); PrintWriter writer = new PrintWriter(str); try { ex.printStackTrace(writer); return str.getBuffer().toString(); } finally { try { str.close(); writer.close(); } catch (IOException e) { //ignore } } }
From source file:ch.epfl.lsir.xin.test.UserBasedCFTest.java
/** * @param args//from w w w . j a v a 2s . c om */ public static void main(String[] args) throws Exception { // TODO Auto-generated method stub PrintWriter logger = new PrintWriter(".//results//UserBasedCF"); PropertiesConfiguration config = new PropertiesConfiguration(); config.setFile(new File(".//conf//UserBasedCF.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..."); 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."); 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++) { logger.println("Folder: " + folder); System.out.println("Folder: " + folder); 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()); } trainRatingMatrix.calculateGlobalAverage(); trainRatingMatrix.calculateUsersMean(); 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()); } logger.println("Initialize a user based collaborative filtering recommendation model."); UserBasedCF algo = new UserBasedCF(trainRatingMatrix, false, ".//localModels//" + config.getString("NAME")); algo.setLogger(logger); algo.build();//if read local model, no need to build the model algo.saveModel(".//localModels//" + config.getString("NAME")); logger.println("Save the model."); System.out.println(trainRatings.size() + " vs. " + testRatings.size()); 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 (Double.isNaN(prediction)) { System.out.println("no prediction"); continue; } if (prediction > algo.getMaxRating()) prediction = algo.getMaxRating(); if (prediction < algo.getMinRating()) prediction = algo.getMinRating(); 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); logger.flush(); //ranking accuracy if (algo.getTopN() > 0) { HashMap<Integer, ArrayList<ResultUnit>> results = new HashMap<Integer, ArrayList<ResultUnit>>(); for (int i = 0; i < testRatingMatrix.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); } } 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); // MovieLens100k //MAE: 0.7343907480119425 RMSE: 0.9405808357192891 (MovieLens 100K, shrinkage 25, neighbor size 60, PCC) //MAE: 0.7522376630596646 RMSE: 0.9520931265724659 (MovieLens 100K, no shrinkage , neighbor size 40, COSINE) 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(); }