List of usage examples for java.io BufferedWriter write
public void write(int c) throws IOException
From source file:com.mindcognition.mindraider.install.Installer.java
/** * Fix URIs - remove dvorka & savant in order to replace it with user's * hostname./*w ww . ja va 2s. co m*/ * * @param filename * the filename * @todo replace reading/closing file with commons-io functions */ public static void fixUris(String filename) { StringBuffer stringBuffer = new StringBuffer(); BufferedReader in = null; try { // try to start reading in = new BufferedReader(new FileReader(new File(filename))); String line; while ((line = in.readLine()) != null) { stringBuffer.append(line); stringBuffer.append("\n"); } } catch (IOException e) { logger.debug(Messages.getString("Installer.unableToReadFile", filename), e); } finally { if (in != null) { try { in.close(); } catch (IOException e1) { logger.debug(Messages.getString("Installer.unableToCloseReader")); } } } // file successfuly loaded - now replace strings String old = stringBuffer.toString(); if (old != null) { String replacement = "http://" + profileHostname + "/e-mentality/mindmap#" + profileUsername; old = old.replaceAll("http://dvorka/e-mentality/mindmap#dvorka", replacement); old = old.replaceAll("http://dvorka/", "http://" + profileHostname + "/"); old = old.replaceAll("http://savant/", "http://" + profileHostname + "/"); // logger.debug(old+"\n"); } // write it back BufferedWriter out = null; try { out = new BufferedWriter(new FileWriter(filename)); out.write(old); } catch (Exception e) { logger.debug(Messages.getString("Installer.unableToWriteFixedFile", filename), e); } finally { if (out != null) { try { out.flush(); out.close(); } catch (IOException e1) { logger.debug(Messages.getString("Installer.unableToCloseFile", filename), e1); } } } }
From source file:com.echopf.ECHOQuery.java
/** * Sends a HTTP request with optional request contents/parameters. * @param path a request url path/*from www . j a v a 2 s . c o m*/ * @param httpMethod a request method (GET/POST/PUT/DELETE) * @param data request contents/parameters * @param multipart use multipart/form-data to encode the contents * @throws ECHOException */ public static InputStream requestRaw(String path, String httpMethod, JSONObject data, boolean multipart) throws ECHOException { final String secureDomain = ECHO.secureDomain; if (secureDomain == null) throw new IllegalStateException("The SDK is not initialized.Please call `ECHO.initialize()`."); String baseUrl = new StringBuilder("https://").append(secureDomain).toString(); String url = new StringBuilder(baseUrl).append("/").append(path).toString(); HttpsURLConnection httpClient = null; try { URL urlObj = new URL(url); StringBuilder apiUrl = new StringBuilder(baseUrl).append(urlObj.getPath()).append("/rest_api=1.0/"); // Append the QueryString contained in path boolean isContainQuery = urlObj.getQuery() != null; if (isContainQuery) apiUrl.append("?").append(urlObj.getQuery()); // Append the QueryString from data if (httpMethod.equals("GET") && data != null) { boolean firstItem = true; Iterator<?> iter = data.keys(); while (iter.hasNext()) { if (firstItem && !isContainQuery) { firstItem = false; apiUrl.append("?"); } else { apiUrl.append("&"); } String key = (String) iter.next(); String value = data.optString(key); apiUrl.append(key); apiUrl.append("="); apiUrl.append(value); } } URL urlConn = new URL(apiUrl.toString()); httpClient = (HttpsURLConnection) urlConn.openConnection(); } catch (IOException e) { throw new ECHOException(e); } final String appId = ECHO.appId; final String appKey = ECHO.appKey; final String accessToken = ECHO.accessToken; if (appId == null || appKey == null) throw new IllegalStateException("The SDK is not initialized.Please call `ECHO.initialize()`."); InputStream responseInputStream = null; try { httpClient.setRequestMethod(httpMethod); httpClient.addRequestProperty("X-ECHO-APP-ID", appId); httpClient.addRequestProperty("X-ECHO-APP-KEY", appKey); // Set access token if (accessToken != null && !accessToken.isEmpty()) httpClient.addRequestProperty("X-ECHO-ACCESS-TOKEN", accessToken); // Build content if (!httpMethod.equals("GET") && data != null) { httpClient.setDoOutput(true); httpClient.setChunkedStreamingMode(0); // use default chunk size if (multipart == false) { // application/json httpClient.addRequestProperty("CONTENT-TYPE", "application/json"); BufferedWriter wrBuffer = new BufferedWriter( new OutputStreamWriter(httpClient.getOutputStream())); wrBuffer.write(data.toString()); wrBuffer.close(); } else { // multipart/form-data final String boundary = "*****" + UUID.randomUUID().toString() + "*****"; final String twoHyphens = "--"; final String lineEnd = "\r\n"; final int maxBufferSize = 1024 * 1024 * 3; httpClient.setRequestMethod("POST"); httpClient.addRequestProperty("CONTENT-TYPE", "multipart/form-data; boundary=" + boundary); final DataOutputStream outputStream = new DataOutputStream(httpClient.getOutputStream()); try { JSONObject postData = new JSONObject(); postData.putOpt("method", httpMethod); postData.putOpt("data", data); new Object() { public void post(JSONObject data, List<String> currentKeys) throws JSONException, IOException { Iterator<?> keys = data.keys(); while (keys.hasNext()) { String key = (String) keys.next(); List<String> newKeys = new ArrayList<String>(currentKeys); newKeys.add(key); Object val = data.get(key); // convert JSONArray into JSONObject if (val instanceof JSONArray) { JSONArray array = (JSONArray) val; JSONObject val2 = new JSONObject(); for (Integer i = 0; i < array.length(); i++) { val2.putOpt(i.toString(), array.get(i)); } val = val2; } // build form-data name String name = ""; for (int i = 0; i < newKeys.size(); i++) { String key2 = newKeys.get(i); name += (i == 0) ? key2 : "[" + key2 + "]"; } if (val instanceof ECHOFile) { ECHOFile file = (ECHOFile) val; if (file.getLocalBytes() == null) continue; InputStream fileInputStream = new ByteArrayInputStream( file.getLocalBytes()); if (fileInputStream != null) { String mimeType = URLConnection .guessContentTypeFromName(file.getFileName()); // write header outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + file.getFileName() + "\"" + lineEnd); outputStream.writeBytes("Content-Type: " + mimeType + lineEnd); outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd); outputStream.writeBytes(lineEnd); // write content int bytesAvailable, bufferSize, bytesRead; do { bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); byte[] buffer = new byte[bufferSize]; bytesRead = fileInputStream.read(buffer, 0, bufferSize); if (bytesRead <= 0) break; outputStream.write(buffer, 0, bufferSize); } while (true); fileInputStream.close(); outputStream.writeBytes(lineEnd); } } else if (val instanceof JSONObject) { this.post((JSONObject) val, newKeys); } else { String data2 = null; try { // in case of boolean boolean bool = data.getBoolean(key); data2 = bool ? "true" : ""; } catch (JSONException e) { // if the value is not a Boolean or the String "true" or "false". data2 = val.toString().trim(); } // write header outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.writeBytes( "Content-Disposition: form-data; name=\"" + name + "\"" + lineEnd); outputStream .writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd); outputStream.writeBytes("Content-Length: " + data2.length() + lineEnd); outputStream.writeBytes(lineEnd); // write content byte[] bytes = data2.getBytes(); for (int i = 0; i < bytes.length; i++) { outputStream.writeByte(bytes[i]); } outputStream.writeBytes(lineEnd); } } } }.post(postData, new ArrayList<String>()); } catch (JSONException e) { throw new ECHOException(e); } finally { outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.flush(); outputStream.close(); } } } else { httpClient.addRequestProperty("CONTENT-TYPE", "application/json"); } if (httpClient.getResponseCode() != -1 /*== HttpURLConnection.HTTP_OK*/) { responseInputStream = httpClient.getInputStream(); } } catch (IOException e) { // get http response code int errorCode = -1; try { errorCode = httpClient.getResponseCode(); } catch (IOException e1) { throw new ECHOException(e1); } // get error contents JSONObject responseObj; try { String jsonStr = ECHOQuery.getResponseString(httpClient.getErrorStream()); responseObj = new JSONObject(jsonStr); } catch (JSONException e1) { if (errorCode == 404) { throw new ECHOException(ECHOException.RESOURCE_NOT_FOUND, "Resource not found."); } throw new ECHOException(ECHOException.INVALID_JSON_FORMAT, "Invalid JSON format."); } // if (responseObj != null) { int code = responseObj.optInt("error_code"); String message = responseObj.optString("error_message"); if (code != 0 || !message.equals("")) { JSONObject details = responseObj.optJSONObject("error_details"); if (details == null) { throw new ECHOException(code, message); } else { throw new ECHOException(code, message, details); } } } throw new ECHOException(e); } return responseInputStream; }
From source file:com.almarsoft.GroundhogReader.lib.ServerManager.java
private static String saveMessageToOutbox(String fullMessage, Context context) { String error = null;/*from w w w . j a va 2 s. c om*/ long outid = DBUtils.insertOfflineSentPost(context); String outputDir = UsenetConstants.EXTERNALSTORAGE + "/" + UsenetConstants.APPNAME + "/offlinecache/outbox/"; File outDir = new File(outputDir); if (!outDir.exists()) outDir.mkdirs(); File outFile = new File(outDir, Long.toString(outid)); BufferedWriter out = null; try { FileWriter writer = new FileWriter(outFile); out = new BufferedWriter(writer); out.write(fullMessage); out.flush(); } catch (IOException e) { error = e.getMessage(); } finally { try { if (out != null) out.close(); } catch (IOException e) { } } return error; }
From source file:ml.shifu.shifu.fs.ShifuFileUtils.java
public static void writeLines(@SuppressWarnings("rawtypes") Collection collection, String filePath, SourceType sourceType) throws IOException { BufferedWriter writer = getWriter(filePath, sourceType); try {/*from w w w . ja v a 2 s . c om*/ for (Object object : collection) { if (object != null) { writer.write(object.toString()); writer.newLine(); } } } finally { IOUtils.closeQuietly(writer); } }
From source file:nbayes_mr.NBAYES_MR.java
public static void splitter(String fname) { String filePath = new File("").getAbsolutePath(); Integer count = 0;/*from www . j av a 2s .com*/ try { Scanner s = new Scanner(new File(fname)); while (s.hasNext()) { count++; s.next(); } Integer cnt5 = count / 5; System.out.println(count); System.out.println(cnt5); Scanner sc = new Scanner(new File(fname)); File file1 = new File("/home/hduser/data1.txt"); File file2 = new File("/home/hduser/data2.txt"); File file3 = new File("/home/hduser/data3.txt"); File file4 = new File("/home/hduser/data4.txt"); File file5 = new File("/home/hduser/data5.txt"); file1.createNewFile(); file2.createNewFile(); file3.createNewFile(); file4.createNewFile(); file5.createNewFile(); FileWriter fw1 = new FileWriter(file1.getAbsoluteFile()); BufferedWriter bw1 = new BufferedWriter(fw1); FileWriter fw2 = new FileWriter(file2.getAbsoluteFile()); BufferedWriter bw2 = new BufferedWriter(fw2); FileWriter fw3 = new FileWriter(file3.getAbsoluteFile()); BufferedWriter bw3 = new BufferedWriter(fw3); FileWriter fw4 = new FileWriter(file4.getAbsoluteFile()); BufferedWriter bw4 = new BufferedWriter(fw4); FileWriter fw5 = new FileWriter(file5.getAbsoluteFile()); BufferedWriter bw5 = new BufferedWriter(fw5); for (int i = 0; i < cnt5; i++) { String l = sc.next(); bw1.write(l + "\n"); } for (int i = cnt5; i < 2 * cnt5; i++) { bw2.write(sc.next() + "\n"); } for (int i = 2 * cnt5; i < 3 * cnt5; i++) { bw3.write(sc.next() + "\n"); } for (int i = 3 * cnt5; i < 4 * cnt5; i++) { bw4.write(sc.next() + "\n"); } for (int i = 4 * cnt5; i < count; i++) { bw5.write(sc.next() + "\n"); } bw1.close(); bw2.close(); bw3.close(); bw4.close(); bw5.close(); sc.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:de.tudarmstadt.ukp.dkpro.tc.mallet.util.MalletUtils.java
public static void outputPredictions(TransducerEvaluator eval, File fileTest, File filePredictions, String predictionClassLabelName) throws IOException { ArrayList<String> predictedLabels = ((PerClassEvaluator) eval).getPredictedLabels(); BufferedReader br = new BufferedReader( new InputStreamReader(new GZIPInputStream(new FileInputStream(fileTest)), "UTF-8")); BufferedWriter bw = new BufferedWriter( new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(filePredictions)), "UTF-8")); String line;//from w ww.j av a 2 s. c o m boolean header = false; int i = 0; while ((line = br.readLine()) != null) { if (!header) { bw.write(line + " " + predictionClassLabelName); bw.flush(); header = true; continue; } if (!line.isEmpty()) { bw.write("\n" + line + " " + predictedLabels.get(i++)); bw.flush(); } else { bw.write("\n"); bw.flush(); } } br.close(); bw.close(); }
From source file:com.twinsoft.convertigo.engine.util.ProjectUtils.java
public static void makeReplacementsInFile(List<Replacement> replacements, String filePath) throws Exception { File file = new File(filePath); if (file.exists()) { String line;//from w w w. j a va2s . c o m StringBuffer sb = new StringBuffer(); BufferedReader br = new BufferedReader(new FileReader(filePath)); while ((line = br.readLine()) != null) { for (Replacement replacement : replacements) { String lineBegin = replacement.getStartsWith(); if ((lineBegin == null) || (line.trim().startsWith(lineBegin))) { line = line.replaceAll(replacement.getSource(), replacement.getTarget()); } } sb.append(line + "\n"); } br.close(); BufferedWriter out = new BufferedWriter(new FileWriter(filePath)); out.write(sb.toString()); out.close(); } else { throw new Exception("File \"" + filePath + "\" does not exist"); } }
From source file:ml.shifu.shifu.fs.ShifuFileUtils.java
public static void copyToLocal(SourceFile sourceFile, String partFilePrefix, String localOutputPath) throws IOException { HdfsPartFile hdfsPartFile = new HdfsPartFile(sourceFile.getPath(), sourceFile.getSourceType(), partFilePrefix);/*from ww w .j av a 2 s .c o m*/ BufferedWriter writer = new BufferedWriter(new FileWriter(localOutputPath)); String line = null; try { while ((line = hdfsPartFile.readLine()) != null) { writer.write(line); writer.newLine(); } } catch (Exception e) { // ignore } finally { IOUtils.closeQuietly(writer); hdfsPartFile.close(); } }
From source file:net.librec.util.FileUtil.java
/** * Write a string into a file with the given path and content. * * @param filePath path of the file//www . j ava2 s . co m * @param content content to write * @param append whether append * @throws Exception if error occurs */ public static void writeString(String filePath, String content, boolean append) throws Exception { String dirPath = filePath.substring(0, filePath.lastIndexOf("/") + 1); File dir = new File(dirPath); if (!dir.exists()) { dir.mkdirs(); } BufferedWriter bw = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(filePath, append), "UTF-8")); if (content.endsWith("\n")) bw.write(content); else bw.write(content + "\n"); bw.close(); }
From source file:anotadorderelacoes.model.UtilidadesPacotes.java
/** * Converte um arquivo de texto puro para o formato JSON aceito pela ARS. * O arquivo de texto deve conter uma sentena por linha. * * @param arquivoTexto Arquivo de texto puro * @param arquivoSaida Arquivo de texto convertido para o formato JSON */// www . ja v a 2 s . c o m public static void converterTextoJson(File arquivoTexto, File arquivoSaida) { BufferedReader br; BufferedWriter bw; String linha; int contadorSentencas = 1; try { //br = new BufferedReader( new FileReader( arquivoTexto ) ); br = new BufferedReader(new InputStreamReader(new FileInputStream(arquivoTexto), "UTF-8")); //bw = new BufferedWriter( new FileWriter( arquivoSaida ) ); bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(arquivoSaida), "UTF-8")); bw.write("# Arquivo \"" + arquivoTexto.getName() + "\" convertido para o formato JSON\n"); bw.write("===\n"); // Uma sentena por linha while ((linha = br.readLine()) != null) { JSONObject sentenca = new JSONObject(); JSONArray tokens = new JSONArray(); sentenca.put("id", contadorSentencas++); sentenca.put("texto", linha); sentenca.put("comentarios", ""); sentenca.put("termos", new JSONArray()); sentenca.put("relacoes", new JSONArray()); sentenca.put("anotadores", new JSONArray()); sentenca.put("anotada", false); sentenca.put("ignorada", false); // Separao simples de tokens for (String token : linha.split(" ")) tokens.add(novoToken(token, token, null, null)); sentenca.put("tokens", tokens); bw.write(sentenca.toString() + "\n"); } bw.close(); br.close(); Logger.getLogger("ARS logger").log(Level.INFO, "Arquivo JSON \"{0}\" gravado.", arquivoSaida.getAbsolutePath()); } catch (FileNotFoundException ex) { Logger.getLogger("ARS logger").log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger("ARS logger").log(Level.SEVERE, null, ex); } }