List of usage examples for java.io BufferedWriter close
@SuppressWarnings("try") public void close() throws IOException
From source file:com.ibm.bi.dml.runtime.util.MapReduceTool.java
public static void writeBooleanToHDFS(boolean b, String filename) throws IOException { BufferedWriter br = setupOutputFile(filename); String line = "" + b; br.write(line);//from w ww . ja va 2s.co m br.close(); }
From source file:com.ibm.bi.dml.runtime.util.MapReduceTool.java
public static void writeStringToHDFS(String s, String filename) throws IOException { BufferedWriter br = setupOutputFile(filename); String line = "" + s; br.write(line);//from w w w . ja v a2 s .c om br.close(); }
From source file:com.murrayc.galaxyzoo.app.provider.client.ZooniverseClient.java
private static void writeParamsToHttpPost(final HttpURLConnection conn, final List<NameValuePair> nameValuePairs) throws IOException { OutputStream out = null;/*from ww w. j a v a2 s. c o m*/ try { out = conn.getOutputStream(); BufferedWriter writer = null; try { writer = new BufferedWriter(new OutputStreamWriter(out, Utils.STRING_ENCODING)); writer.write(getPostDataBytes(nameValuePairs)); writer.flush(); } finally { if (writer != null) { writer.close(); } } } finally { if (out != null) { try { out.close(); } catch (final IOException e) { Log.error("writeParamsToHttpPost(): Exception while closing out", e); } } } }
From source file:data_gen.Data_gen.java
public static void generate_xml() { SchemaGenerator schema = new SchemaGenerator(schema_fields); try {//ww w.j a v a 2s . c o m String content = schema.generateSchema(); File file = new File(output_dir + "/" + "schema.xml"); if (!file.exists()) { file.createNewFile(); } FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); bw.write(content); bw.close(); } catch (IOException e) { System.out.println("There was an error writing to the xml file." + "\n"); } }
From source file:cgs_lda_multicore.DataModel.DataPreparation.java
/** * Simply write the dataset from LDADataset to data file in this lib format. * /* w w w . j a v a 2 s. co m*/ * @param data * @param dir * @param dfile * @return * @throws Exception */ public static boolean writeDataset(LDADataset data, String dir, String dfile) throws Exception { try { BufferedWriter writer = new BufferedWriter(new FileWriter(dir + File.separator + dfile)); writer.write(String.valueOf(data.M)); writer.write("\n"); for (int i = 0; i < data.M; i++) { for (int j = 0; j < data.docs[i].length; j++) { writer.write(data.localDict.getWord(data.docs[i].words[j]) + " "); } writer.write("\n"); } writer.close(); } catch (Exception e) { System.out.println("Error while writing dataset: " + e.getMessage()); e.printStackTrace(); return false; } return true; }
From source file:canreg.client.analysis.Tools.java
public static LinkedList<String> generateRChart(Collection<CancerCasesCount> casesCounts, String fileName, String header, FileTypes fileType, ChartType chartType, boolean includeOther, Double restCount, String rpath, boolean sortByCount, String xlab) { LinkedList<String> generatedFiles = new LinkedList<String>(); RFileBuilder rff = new RFileBuilder(); File script = new File(Globals.R_SCRIPTS_PATH + "/makeSureGgplot2IsInstalled.r"); rff.appendHeader(script.getAbsolutePath()); rff.appendFileTypePart(fileType, fileName); generatedFiles.add(fileName);/* w w w .jav a2 s . com*/ rff.appendData(casesCounts, restCount, includeOther); int numberOfCategories = casesCounts.size(); if (includeOther) { numberOfCategories += 1; } if (sortByCount) { rff.appendSort(chartType, numberOfCategories, includeOther, restCount); } rff.appendPlots(chartType, header, xlab); rff.appendWriteOut(); System.out.println(rff.getScript()); try { File tempFile = File.createTempFile("script", ".r"); // generatedFiles.add(tempFile.getPath()); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(tempFile), "UTF8")); writer.append(rff.getScript()); writer.close(); Tools.callR(tempFile.getAbsolutePath(), rpath, fileName + "-report.txt"); } catch (TableErrorException ex) { Logger.getLogger(TopNChartTableBuilder.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(TopNChartTableBuilder.class.getName()).log(Level.SEVERE, null, ex); } return generatedFiles; }
From source file:net.iharding.utils.FileUtils.java
/** * /*w w w. j a va 2 s. c o m*/ * @param content * @param filePath */ public static void writeFile(String content, String filePath) { try { if (FileUtils.createFile(filePath)) { // FileWriter fileWriter = new FileWriter(filePath, true); // BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); //??? OutputStreamWriter fileWriter = new OutputStreamWriter(new FileOutputStream(filePath), "UTF-8"); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); bufferedWriter.write(content); bufferedWriter.close(); fileWriter.close(); } else { log.info("??"); } } catch (Exception e) { e.printStackTrace(); } }
From source file:uk.ac.bbsrc.tgac.miso.integration.util.IntegrationUtils.java
/** * Sends a String message to a given host socket * //w w w . j a v a 2 s . c o m * @param socket * of type Socket * @param query * of type String * @return String * @throws IntegrationException * when the socket couldn't be created */ public static String sendMessage(Socket socket, String query) throws IntegrationException { BufferedWriter wr = null; BufferedReader rd = null; try { wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8")); // Send data wr.write(query + "\r\n"); wr.flush(); // Get response rd = new BufferedReader(new InputStreamReader(socket.getInputStream())); String line; StringBuilder sb = new StringBuilder(); while ((line = rd.readLine()) != null) { sb.append(line); } wr.close(); rd.close(); String dirty = sb.toString(); StringBuilder response = new StringBuilder(); int codePoint; int i = 0; while (i < dirty.length()) { codePoint = dirty.codePointAt(i); if ((codePoint == 0x9) || (codePoint == 0xA) || (codePoint == 0xD) || ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) || ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) || ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF))) { response.append(Character.toChars(codePoint)); } i += Character.charCount(codePoint); } return response.toString().replace("\\\n", "").replace("\\\t", ""); } catch (UnknownHostException e) { log.error("Cannot resolve host: " + socket.getInetAddress(), e); throw new IntegrationException(e.getMessage()); } catch (IOException e) { log.error("Couldn't get I/O for the connection to: " + socket.getInetAddress(), e); throw new IntegrationException(e.getMessage()); } finally { try { if (wr != null) { wr.close(); } if (rd != null) { rd.close(); } } catch (Throwable t) { log.error("close socket", t); } } }
From source file:de.unibi.techfak.bibiserv.util.codegen.Main.java
/** * Copy a text based file from in to out and replace TEMPLATE_ID with 'id' * and TEMPLATE_NAME with 'name'// w w w.j a v a 2 s. c o m * * * @param in * @param out * @param id * @param name * @throws IOException */ public static void CopyAndReplace(InputStream in, OutputStream out, String id, String name, String version) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out)); String line; while ((line = br.readLine()) != null) { bw.append(line.replace("TEMPLATE_ID", id).replace("TEMPLATE_NAME", name).replace("TEMPLATE_VERSION", version)); bw.newLine(); } br.close(); bw.close(); }
From source file:com.clutch.ClutchSync.java
public static void sync(ClutchStats clutchStats) { if (thisIsHappening) { return;/* ww w .ja v a 2 s .co m*/ } thisIsHappening = true; if (pendingReload) { pendingReload = false; for (ClutchView clutchView : clutchViews) { clutchView.contentChanged(); } } ClutchAPIClient.callMethod("sync", null, new ClutchAPIResponseHandler() { @Override public void onSuccess(JSONObject response) { final AssetManager mgr = context.getAssets(); File parentCacheDir = context.getCacheDir(); final File tempDir; try { tempDir = File.createTempFile("clutchtemp", Long.toString(System.nanoTime()), parentCacheDir); if (!tempDir.delete()) { Log.e(TAG, "Could not delete temp file: " + tempDir.getAbsolutePath()); return; } if (!tempDir.mkdir()) { Log.e(TAG, "Could not create temp directory: " + tempDir.getAbsolutePath()); return; } } catch (IOException e) { Log.e(TAG, "Could not create temp file"); return; } File cacheDir = getCacheDir(); if (cacheDir == null) { try { if (!copyAssetDir(mgr, tempDir)) { return; } } catch (IOException e) { Log.e(TAG, "Couldn't copy the asset dir files to the temp dir: " + e); return; } } else { try { if (!copyDir(cacheDir, tempDir)) { return; } } catch (IOException e) { Log.e(TAG, "Couldn't copy the cache dir files to the temp dir: " + e); return; } } conf = response.optJSONObject("conf"); String version = "" + conf.optInt("_version"); newFilesDownloaded = false; try { JSONCompareResult confCompare = JSONCompare.compareJSON(ClutchConf.getConf(), conf, JSONCompareMode.NON_EXTENSIBLE); if (confCompare.failed()) { newFilesDownloaded = true; // This is where in the ObjC version we write out the conf, but I don't think we need to anymore } } catch (JSONException e1) { Log.i(TAG, "Couldn't compare the conf file with the cached conf file: " + e1); } File cachedFiles = new File(tempDir, "__files.json"); JSONObject cached = null; if (cachedFiles.exists()) { StringBuffer strContent = new StringBuffer(""); try { FileInputStream in = new FileInputStream(cachedFiles); int ch; while ((ch = in.read()) != -1) { strContent.append((char) ch); } in.close(); cached = new JSONObject(new JSONTokener(strContent.toString())); } catch (IOException e) { Log.e(TAG, "Could not read __files.json from cache file: " + e); } catch (JSONException e) { Log.e(TAG, "Could not parse __files.json from cache file: " + e); } } if (cached == null) { cached = new JSONObject(); } final JSONObject files = response.optJSONObject("files"); try { JSONCompareResult filesCompare = JSONCompare.compareJSON(cached, files, JSONCompareMode.NON_EXTENSIBLE); if (filesCompare.passed()) { complete(tempDir, files); return; } } catch (JSONException e1) { Log.i(TAG, "Couldn't compare the file hash list with the cached file hash list: " + e1); } try { BufferedWriter bw = new BufferedWriter(new FileWriter(cachedFiles)); bw.write(files.toString()); bw.flush(); bw.close(); } catch (FileNotFoundException e) { } catch (IOException e) { } currentFile = 0; final int numFiles = files.length(); Iterator<?> it = files.keys(); while (it.hasNext()) { final String fileName = (String) it.next(); final String hash = files.optString(fileName); final String prevHash = cached.optString(fileName); // If they equal, then just continue if (hash.equals(prevHash)) { if (++currentFile == numFiles) { complete(tempDir, files); return; } continue; } // Looks like we've seen a new file, so we should reload when this is all done newFilesDownloaded = true; // Otherwise we need to download the new file ClutchAPIClient.downloadFile(fileName, version, new ClutchAPIDownloadResponseHandler() { @Override public void onSuccess(String response) { try { File fullFile = new File(tempDir, fileName); fullFile.getParentFile().mkdirs(); fullFile.createNewFile(); BufferedWriter bw = new BufferedWriter(new FileWriter(fullFile)); bw.write(response); bw.flush(); bw.close(); } catch (IOException e) { final Writer result = new StringWriter(); final PrintWriter printWriter = new PrintWriter(result); e.printStackTrace(printWriter); Log.e(TAG, "Tried, but could not write file: " + fileName + " : " + result); } if (++currentFile == numFiles) { complete(tempDir, files); return; } } @Override public void onFailure(Throwable e, String content) { final Writer result = new StringWriter(); final PrintWriter printWriter = new PrintWriter(result); e.printStackTrace(printWriter); Log.e(TAG, "Error downloading file from server: " + fileName + " " + result + " " + content); if (++currentFile == numFiles) { complete(tempDir, files); return; } } }); } } @Override public void onFailure(Throwable e, JSONObject errorResponse) { Log.e(TAG, "Failed to sync with the Clutch server: " + errorResponse); } }); background(clutchStats); }