List of usage examples for java.io BufferedWriter newLine
public void newLine() throws IOException
From source file:net.arccotangent.pacchat.net.Client.java
public static void sendMessage(String msg, String ip_address) { client_log.i("Sending message to " + ip_address); client_log.i("Connecting to server..."); PublicKey pub;//from w w w . j a va 2 s .c om PrivateKey priv; Socket socket; BufferedReader input; BufferedWriter output; client_log.i("Checking for recipient's public key..."); if (KeyManager.checkIfIPKeyExists(ip_address)) { client_log.i("Public key found."); } else { client_log.i("Public key not found, requesting key from their server."); try { Socket socketGetkey = new Socket(); socketGetkey.connect(new InetSocketAddress(InetAddress.getByName(ip_address), Server.PORT), 1000); BufferedReader inputGetkey = new BufferedReader( new InputStreamReader(socketGetkey.getInputStream())); BufferedWriter outputGetkey = new BufferedWriter( new OutputStreamWriter(socketGetkey.getOutputStream())); outputGetkey.write("301 getkey"); outputGetkey.newLine(); outputGetkey.flush(); String pubkeyB64 = inputGetkey.readLine(); byte[] pubEncoded = Base64.decodeBase64(pubkeyB64); X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubEncoded); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); outputGetkey.close(); inputGetkey.close(); KeyManager.saveKeyByIP(ip_address, keyFactory.generatePublic(pubSpec)); } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e) { client_log.e("Error saving recipient's key!"); e.printStackTrace(); } } try { socket = new Socket(); socket.connect(new InetSocketAddress(InetAddress.getByName(ip_address), Server.PORT), 1000); input = new BufferedReader(new InputStreamReader(socket.getInputStream())); output = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); } catch (SocketTimeoutException e) { client_log.e("Connection to server timed out!"); e.printStackTrace(); return; } catch (ConnectException e) { client_log.e("Connection to server was refused!"); e.printStackTrace(); return; } catch (UnknownHostException e) { client_log.e("You entered an invalid IP address!"); e.printStackTrace(); return; } catch (IOException e) { client_log.e("Error connecting to server!"); e.printStackTrace(); return; } try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } pub = KeyManager.loadKeyByIP(ip_address); priv = Main.getKeypair().getPrivate(); String cryptedMsg = MsgCrypto.encryptAndSignMessage(msg, pub, priv); try { client_log.i("Sending message to recipient."); output.write("200 encrypted message"); output.newLine(); output.write(cryptedMsg); output.newLine(); output.flush(); String ack = input.readLine(); switch (ack) { case "201 message acknowledgement": client_log.i("Transmission successful, received server acknowledgement."); break; case "202 unable to decrypt": client_log.e( "Transmission failure! Server reports that the message could not be decrypted. Did your keys change? Asking recipient for key update."); kuc_id++; KeyUpdateClient kuc = new KeyUpdateClient(kuc_id, ip_address); kuc.start(); break; case "203 unable to verify": client_log.w("**********************************************"); client_log.w( "Transmission successful, but the receiving server reports that the authenticity of the message could not be verified!"); client_log.w( "Someone may be tampering with your connection! This is an unlikely, but not impossible scenario!"); client_log.w( "If you are sure the connection was not tampered with, consider requesting a key update."); client_log.w("**********************************************"); break; case "400 invalid transmission header": client_log.e( "Transmission failure! Server reports that the message is invalid. Try updating your software and have the recipient do the same. If this does not fix the problem, report the error to developers."); break; default: client_log.w("Server responded with unexpected code: " + ack); client_log.w("Transmission might not have been successful."); break; } output.close(); input.close(); } catch (IOException e) { client_log.e("Error sending message to recipient!"); e.printStackTrace(); } }
From source file:it.moondroid.chatbot.alice.Sraix.java
public static void log(String pattern, String template) { System.out.println("Logging " + pattern); template = template.trim();//from www .j a va 2s . c o m if (MagicBooleans.cache_sraix) try { if (!template.contains("<year>") && !template.contains("No facilities")) { template = template.replace("\n", "\\#Newline"); template = template.replace(",", MagicStrings.aimlif_split_char_name); template = template.replaceAll("<a(.*)</a>", ""); template = template.trim(); if (template.length() > 0) { FileWriter fstream = new FileWriter("c:/ab/bots/sraixcache/aimlif/sraixcache.aiml.csv", true); BufferedWriter fbw = new BufferedWriter(fstream); fbw.write("0," + pattern + ",*,*," + template + ",sraixcache.aiml"); fbw.newLine(); fbw.close(); } } } catch (Exception e) { System.out.println("Error: " + e.getMessage()); } }
From source file:at.riemers.velocity2js.velocity.Velocity2Js.java
private static void processTemplate(String inputFile, BufferedWriter out, ResourceBundle bundle) throws Exception { log.info("processing: " + inputFile); String functionName = Velocity2Js.createFunctionName(inputFile); generate(inputFile, functionName, out, bundle); out.newLine(); out.newLine();/*from w ww . j a v a 2 s .c om*/ }
From source file:edu.iu.daal_kmeans.regroupallgather.KMUtil.java
/** * Generate centroids and upload to the cDir * /*from w ww.j a v a 2s .co m*/ * @param numCentroids * @param vectorSize * @param configuration * @param random * @param cenDir * @param fs * @throws IOException */ static void generateCentroids(int numCentroids, int vectorSize, Configuration configuration, Path cenDir, FileSystem fs) throws IOException { Random random = new Random(); double[] data = null; if (fs.exists(cenDir)) fs.delete(cenDir, true); if (!fs.mkdirs(cenDir)) { throw new IOException("Mkdirs failed to create " + cenDir.toString()); } data = new double[numCentroids * vectorSize]; for (int i = 0; i < data.length; i++) { data[i] = random.nextDouble() * 1000; } Path initClustersFile = new Path(cenDir, Constants.CENTROID_FILE_NAME); System.out.println("Generate centroid data." + initClustersFile.toString()); FSDataOutputStream out = fs.create(initClustersFile, true); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out)); for (int i = 0; i < data.length; i++) { if ((i % vectorSize) == (vectorSize - 1)) { bw.write(data[i] + ""); bw.newLine(); } else { bw.write(data[i] + " "); } } bw.flush(); bw.close(); System.out.println("Wrote centroids data to file"); }
From source file:biospectra.BioSpectra.java
private static void simulateReads(String[] args) throws Exception { String fastaDir = args[0];/*from ww w .j a v a 2s . co m*/ int readSize = Integer.parseInt(args[1]); double errorRatioStart = Double.parseDouble(args[2]); double errorRatioEnd = Double.parseDouble(args[3]); double errorRatioStep = Double.parseDouble(args[4]); int iteration = Integer.parseInt(args[5]); String outDir = args[6]; List<File> fastaDocs = FastaFileHelper.findFastaDocs(fastaDir); File outDirFile = new File(outDir); if (!outDirFile.exists()) { outDirFile.mkdirs(); } MetagenomicReadGenerator generator = new MetagenomicReadGenerator(fastaDocs); for (double cur = errorRatioStart; cur <= errorRatioEnd; cur += errorRatioStep) { File outFile = new File(outDir + "/sample_" + cur + ".fa"); BufferedWriter bw = new BufferedWriter(new FileWriter(outFile)); for (int i = 0; i < iteration; i++) { FASTAEntry sample = generator.generate(readSize, cur); bw.write(sample.getHeaderLine()); bw.newLine(); bw.write(sample.getSequence()); bw.newLine(); } bw.close(); } }
From source file:io.cslinmiso.line.utils.Utility.java
/** * Java IO (java io write file)//www . j a v a 2s.c om * * @param data * @param fileName * @throws IOException */ public static void writeFile(List<String> data, String fileName) throws IOException { BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), "UTF-8")); try { for (String d : data) { bw.write(d); bw.newLine(); } bw.flush(); } catch (IOException ioe) { throw ioe; } finally { bw.close(); } }
From source file:com.doculibre.constellio.services.ImportExportServicesImpl.java
private static String convertText(String string) { // here, the conversion takes place automatically, // thanks to Java StringReader reader = new StringReader(string); StringWriter writer = new StringWriter(); try {/* w w w . java2 s.c o m*/ BufferedReader bufferedreader = new BufferedReader(reader); BufferedWriter bufferedwriter = new BufferedWriter(writer); String line; while ((line = bufferedreader.readLine()) != null) { bufferedwriter.write(line); bufferedwriter.newLine(); } bufferedreader.close(); bufferedwriter.close(); } catch (IOException e) {/* HANDLE EXCEPTION */ } return writer.toString(); }
From source file:com.ushahidi.android.app.util.Util.java
/** * For debugging purposes. Append content of a string to a file * /*ww w. java2s .c om*/ * @param text */ public static void appendLog(String text) { File logFile = new File(Environment.getExternalStorageDirectory(), "ush_log.txt"); if (!logFile.exists()) { try { logFile.createNewFile(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } try { // BufferedWriter for performance, true to set append to file flag BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true)); buf.append(text); buf.newLine(); buf.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:com.incapture.rapgen.output.OutputWriter.java
/** * Some files are composed of multiple templates. So the map passed in here is filename to template order to template. * E.g. "file.txt"->1->"some code" "file.txt"->2->"other code" and so on. * * @param rootFolder/* w ww . j a v a2s . c o m*/ * @param pathToTemplate */ public static void writeMultiPartTemplates(String rootFolder, Map<String, Map<String, StringTemplate>> pathToTemplate) { // For each file, dump the templates for (Map.Entry<String, Map<String, StringTemplate>> entry : pathToTemplate.entrySet()) { File file = new File(rootFolder, entry.getKey()); file.getParentFile().mkdirs(); BufferedWriter bow = null; try { bow = new BufferedWriter(new FileWriter(file)); Set<String> sections = entry.getValue().keySet(); SortedSet<String> sorted = new TreeSet<String>(); sorted.addAll(sections); for (String sec : sorted) { bow.write(entry.getValue().get(sec).toString()); bow.newLine(); } bow.close(); } catch (IOException e) { System.err.println(e.getMessage()); } finally { if (bow != null) { try { bow.close(); } catch (IOException e) { System.err.println("Error closing output stream: " + ExceptionToString.format(e)); } } } } }
From source file:com.yahoo.ycsb.db.RedisClient.java
public static String decompressWithLog(String st) { // System.out.println("decompress"); // System.out.println(st.substring(0, 20)); long start_time = System.nanoTime(); String ret = decompress(st);/*from ww w . j ava2s.c om*/ try { long end_time = System.nanoTime(); long time = end_time - start_time; BufferedWriter bw = new BufferedWriter(new FileWriter("decompress_time.txt", true)); bw.write("" + time); bw.newLine(); bw.flush(); } catch (Exception e) { } // System.out.println("decompressed"); // System.out.println(ret.substring(0, 20)); return ret; }