List of usage examples for java.io BufferedWriter flush
public void flush() throws IOException
From source file:br.edu.ufcg.supervisor.SupervisorInterface.java
private void saveLogTraining(String content) { logString.replaceAll("<br>", ""); try {/* www . ja v a2 s . co m*/ Time time = new Time(); //String fileName = "supervisorM-"+time.year+time.month+time.weekDay+time.hour+time.minute+time.second+".log"; @SuppressWarnings("static-access") String fileName = "supervisorM-" + time.YEAR + time.MONTH + time.HOUR + time.MINUTE + time.SECOND + ".log"; String folder = Environment.getExternalStorageDirectory().toString() + "/Download/"; BufferedWriter writer = new BufferedWriter(new FileWriter(folder + fileName)); writer.write(content); writer.flush(); writer.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:nc.noumea.mairie.organigramme.services.exportGraphML.impl.ExportGraphMLServiceOrgaFichesPosteImpl.java
private byte[] exportGraphML(FichePosteTreeNodeDto node, boolean isAfficheAgent, Map<String, Boolean> mapIdLiOuvert) throws IOException { DocumentFactory factory = DocumentFactory.getInstance(); Element root = factory.createElement("graphml"); Document document = factory.createDocument(root); document.setXMLEncoding("utf-8"); Element graph = initRoot(root); initHeader(root);//from w w w . j a v a2s . co m construitTableauStats(graph, this.entiteDto); mapFichesPosteSuperieureByService = EntityUtils.getFichesPosteChefDeService(node); buildGraphMlTree(graph, node, mapIdLiOuvert, isAfficheAgent, null); ByteArrayOutputStream os_writer = new ByteArrayOutputStream(); try { BufferedWriter wtr = new BufferedWriter(new OutputStreamWriter(os_writer, "UTF-8")); document.write(wtr); wtr.flush(); wtr.close(); } catch (Exception e) { throw new RuntimeException(e); } return os_writer.toByteArray(); }
From source file:org.envirocar.app.application.UploadManager.java
/** * Saves a json object to the sd card//from www . j av a 2s . c o m * * @param obj * the object to save * @param id */ private File saveToSdCard(String obj, String id) { File log = new File(context.getExternalFilesDir(null), "enviroCar-track-" + id + ".json"); try { BufferedWriter out = new BufferedWriter(new FileWriter(log.getAbsolutePath(), false)); out.write(obj); out.flush(); out.close(); return log; } catch (IOException e) { logger.warn(e.getMessage(), e); } return null; }
From source file:com.sludev.commons.vfs2.provider.azure.AzFileProviderTest.java
/** * //from w w w .j a v a2s . c om */ @Test public void A001_uploadFile() throws Exception { String currAccountStr = testProperties.getProperty("azure.account.name"); String currKey = testProperties.getProperty("azure.account.key"); String currContainerStr = testProperties.getProperty("azure.test0001.container.name"); String currHost = testProperties.getProperty("azure.host"); // <account>.blob.core.windows.net String currFileNameStr; File temp = File.createTempFile("uploadFile01", ".tmp"); try (FileWriter fw = new FileWriter(temp)) { BufferedWriter bw = new BufferedWriter(fw); bw.append("testing..."); bw.flush(); } DefaultFileSystemManager currMan = new DefaultFileSystemManager(); currMan.addProvider(AzConstants.AZSBSCHEME, new AzFileProvider()); currMan.addProvider("file", new DefaultLocalFileProvider()); currMan.init(); StaticUserAuthenticator auth = new StaticUserAuthenticator("", currAccountStr, currKey); FileSystemOptions opts = new FileSystemOptions(); DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth); currFileNameStr = "test01.tmp"; String currUriStr = String.format("%s://%s/%s/%s", AzConstants.AZSBSCHEME, currHost, currContainerStr, currFileNameStr); FileObject currFile = currMan.resolveFile(currUriStr, opts); FileObject currFile2 = currMan.resolveFile(String.format("file://%s", temp.getAbsolutePath())); currFile.copyFrom(currFile2, Selectors.SELECT_SELF); temp.delete(); }
From source file:com.linkedin.pinot.controller.helix.ControllerTest.java
public JSONObject postQuery(String query, String brokerBaseApiUrl) throws Exception { final JSONObject json = new JSONObject(); json.put("pql", query); json.put("trace", isTraceEnabled); // json.put("debugOptions", "routingOptions=FORCE_LLC,FORCE_HLC;otherOption=foo,bar"); final long start = System.currentTimeMillis(); final URLConnection conn = new URL(brokerBaseApiUrl + "/query").openConnection(); conn.setDoOutput(true);//from www. j a va2s . c o m final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8")); final String reqStr = json.toString(); writer.write(reqStr, 0, reqStr.length()); writer.flush(); JSONObject ret = getBrokerReturnJson(conn); final long stop = System.currentTimeMillis(); LOGGER.debug("Time taken for '{}':{}ms", query, (stop - start)); return ret; }
From source file:gr.auth.ee.lcs.evaluators.FileLogger.java
@Override public final double getMetric(final AbstractLearningClassifierSystem lcs) { final double evalResult = actualEvaluator.getMetric(lcs); try {/* w w w . j a va 2 s . c om*/ final FileWriter fstream = new FileWriter(file, true); final BufferedWriter buffer = new BufferedWriter(fstream); buffer.write(/* String.valueOf(lcs.repetition) + ":" + */String.valueOf(evalResult) + System.getProperty("line.separator")); buffer.flush(); buffer.close(); } catch (Exception e) { e.printStackTrace(); } return 0; }
From source file:com.mercandalli.android.apps.files.common.net.TaskPost.java
@Override protected String doInBackground(Void... urls) { try {/*from ww w. jav a 2 s .c o m*/ if (this.mParameters != null) { if (!StringUtils.isNullOrEmpty(Config.getNotificationId())) { mParameters.add(new StringPair("android_id", "" + Config.getNotificationId())); } url = NetUtils.addUrlParameters(url, mParameters); } Log.d("TaskGet", "url = " + url); final URL tmpUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) tmpUrl.openConnection(); conn.setReadTimeout(10_000); conn.setConnectTimeout(15_000); conn.setRequestMethod("POST"); conn.setRequestProperty("Authorization", "Basic " + Config.getUserToken()); conn.setUseCaches(false); conn.setDoInput(true); conn.setDoOutput(true); if (this.mParameters != null) { final OutputStream outputStream = conn.getOutputStream(); final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8")); writer.write(getQuery(mParameters)); writer.flush(); writer.close(); outputStream.close(); } conn.connect(); // Starts the query int responseCode = conn.getResponseCode(); InputStream inputStream = new BufferedInputStream(conn.getInputStream()); // convert inputstream to string String resultString = convertInputStreamToString(inputStream); //int responseCode = response.getStatusLine().getStatusCode(); if (responseCode >= 300) { resultString = "Status Code " + responseCode + ". " + resultString; } conn.disconnect(); return resultString; } catch (IOException e) { Log.e(getClass().getName(), "Failed to convert Json", e); } return null; // try { // // // http://stackoverflow.com/questions/9767952/how-to-add-parameters-to-httpurlconnection-using-post // // HttpPost httppost = new HttpPost(url); // // MultipartEntity mpEntity = new MultipartEntity(); // if (this.file != null) mpEntity.addPart("file", new FileBody(file, "*/*")); // // String log_parameters = ""; // if (this.parameters != null) // for (StringPair b : parameters) { // mpEntity.addPart(b.getName(), new StringBody(b.getValue(), Charset.forName("UTF-8"))); // log_parameters += b.getName() + ":" + b.getValue() + " "; // } // Log.d("TaskPost", "url = " + url + " " + log_parameters); // // httppost.setEntity(mpEntity); // // StringBuilder authentication = new StringBuilder().append(app.getConfig().getUser().getAccessLogin()).append(":").append(app.getConfig().getUser().getAccessPassword()); // String result = Base64.encodeBytes(authentication.toString().getBytes()); // httppost.setHeader("Authorization", "Basic " + result); // // HttpClient httpclient = new DefaultHttpClient(); // HttpResponse response = httpclient.execute(httppost); // // // receive response as inputStream // InputStream inputStream = response.getEntity().getContent(); // // String resultString = null; // // // convert inputstream to string // if (inputStream != null) // resultString = convertInputStreamToString(inputStream); // // int responseCode = response.getStatusLine().getStatusCode(); // if (responseCode >= 300) // resultString = "Status Code " + responseCode + ". " + resultString; // return resultString; // // // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } catch (ClientProtocolException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // return null; }
From source file:com.cloudant.tests.util.SimpleHttpServer.java
/** * Write a simple OK response/*from w ww . j a v a 2 s. co m*/ * * @param os * @throws IOException */ protected void writeOK(OutputStream os) throws IOException { BufferedWriter w = new BufferedWriter(new OutputStreamWriter(os)); //note the HTTP spec says the status line must be followed by a CRLF //and an empty line must separate headers from optional body //so basically we need 2 CRLFs w.write("HTTP/1.0 200 OK\r\n\r\n"); w.flush(); }
From source file:net.atomique.ksar.ui.GraphView.java
private void csvButtonActionPerformed(java.awt.event.ActionEvent evt) { //GEN-FIRST:event_csvButtonActionPerformed String filename = null;//from ww w.j a va2 s .c o m String buffer = null; filename = askSaveFilename("Export CSV", Config.getLastExportDirectory()); if (filename == null) { return; } Config.setLastExportDirectory(filename); if (!Config.getLastExportDirectory().isDirectory()) { Config.setLastExportDirectory(Config.getLastExportDirectory().getParentFile()); Config.save(); } buffer = thegraph.make_csv(); if (GlobalOptions.isDodebug()) { log.debug(buffer); } BufferedWriter out = null; try { out = new BufferedWriter(new FileWriter(filename)); } catch (IOException e) { out = null; } if (out == null) { return; } try { out.write(buffer); out.flush(); out.close(); } catch (IOException e) { } }
From source file:com.bancvue.mongomigrate.CreateCommand.java
public int execute() { int exitCode = 0; Path file = null;/* w ww .ja va 2s . c om*/ try { // Ensure migrations folder exists. Path folder = Paths.get(migrationsFolder); if (!Files.exists(folder)) { Files.createDirectories(folder); } // Generate filename and ensure it doesn't already exist. file = Paths.get(migrationsFolder, generateMigrationFileName(migrationName)); if (Files.exists(file)) throw new FileAlreadyExistsException(file.toAbsolutePath().toString()); // Write the file. BufferedWriter writer = Files.newBufferedWriter(file, Charset.forName("UTF-8")); writer.write("// Add migration javascript here.\n"); writer.write("db.<collection_name>.update(\n"); writer.write(" { <query> },\n"); writer.write(" { <update> },\n"); writer.write(" { multi: true }\n"); writer.write(");\n"); writer.flush(); writer.close(); System.out.println("Created migration file: " + file.toString()); } catch (FileAlreadyExistsException e) { System.err.println("The specified migration file " + file.toString() + " already exists."); exitCode = 1; } catch (IOException e) { e.printStackTrace(); exitCode = 1; } return exitCode; }