List of usage examples for java.io BufferedWriter close
@SuppressWarnings("try") public void close() throws IOException
From source file:fm.last.commons.io.LastFileUtils.java
/** * Appends the passed string to the passed file. * //from ww w. java 2 s . c o m * @param file File to append string to (will be created if it does not exist). * @param string String to append. * @throws IOException If an error occurs appending the string to the file. */ public static void appendStringToFile(File file, String string) throws IOException { BufferedWriter writer = new BufferedWriter(new FileWriter(file, true)); writer.write(string); writer.close(); }
From source file:com.sugarcrm.candybean.datasource.CsvDataAdapterSystemTest.java
private static void createFile(String dir, String filename, String content) { try {//from ww w. ja v a2s .c o m File file = new File(dir + File.separator + filename); // Create file if not exist if (!file.exists()) { file.createNewFile(); System.out.println("createFile(): created " + file.getAbsolutePath()); } else { System.out.println("createFile(): " + file.getAbsolutePath() + " already exists"); } FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); bw.write(content); bw.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:it.iit.genomics.cru.bridges.liftover.ws.LiftOverRun.java
public static Mapping runLiftOver(String genome, String fromAssembly, String toAssembly, String chromosome, int start, int end) { String liftOverCommand = RESOURCE_BUNDLE.getString("liftOverCommand"); String liftOverPath = RESOURCE_BUNDLE.getString("liftOverPath"); String mapChainDir = RESOURCE_BUNDLE.getString("mapChainDir"); String tmpDir = RESOURCE_BUNDLE.getString("tmpDir"); Mapping mapping = null;//from w w w . j a v a2s.c o m Runtime r = Runtime.getRuntime(); String rootFilename = String.format("%s", RandomStringUtils.randomAlphanumeric(8)); String inputFilename = rootFilename + "-" + fromAssembly + ".bed"; String outputFilename = rootFilename + "-" + toAssembly + ".bed"; String unmappedFilename = rootFilename + "-" + "unmapped.bed"; String mapChain = fromAssembly.toLowerCase() + "To" + toAssembly.toUpperCase().charAt(0) + toAssembly.toLowerCase().substring(1) + ".over.chain.gz"; try { File tmpDirFile = new File(tmpDir); // if the directory does not exist, create it if (false == tmpDirFile.exists()) { System.out.println("creating directory: " + tmpDir); boolean result = tmpDirFile.mkdir(); if (result) { System.out.println("DIR created"); } } // Write input bed file File inputFile = new File(tmpDir + inputFilename); // if file doesnt exists, then create it if (!inputFile.exists()) { inputFile.createNewFile(); } FileWriter fw = new FileWriter(inputFile.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); bw.write(chromosome + "\t" + start + "\t" + end + "\n"); bw.close(); String commandArgs = String.format("%s %s %s %s %s", liftOverPath + "/" + liftOverCommand, tmpDir + inputFilename, mapChainDir + mapChain, tmpDir + outputFilename, tmpDir + unmappedFilename); System.out.println(commandArgs); Process p = r.exec(commandArgs); p.waitFor(); BufferedReader b = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = ""; while ((line = b.readLine()) != null) { System.out.println(line); } b.close(); b = new BufferedReader(new FileReader(tmpDir + outputFilename)); while ((line = b.readLine()) != null) { String[] cells = line.split("\t"); String newChromosome = cells[0]; int newStart = Integer.parseInt(cells[1]); int newEnd = Integer.parseInt(cells[2]); mapping = new Mapping(genome, toAssembly, newChromosome, newStart, newEnd); } b.close(); // delete File delete = new File(tmpDir + inputFilename); delete.delete(); delete = new File(tmpDir + outputFilename); delete.delete(); delete = new File(tmpDir + unmappedFilename); delete.delete(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } return mapping; }
From source file:com.example.SampleStreamExample.java
public static void run(String consumerKey, String consumerSecret, String token, String secret) throws InterruptedException { // Create an appropriately sized blocking queue BlockingQueue<String> queue = new LinkedBlockingQueue<String>(10000); // Define our endpoint: By default, delimited=length is set (we need this for our processor) // and stall warnings are on. StatusesSampleEndpoint endpoint = new StatusesSampleEndpoint(); endpoint.stallWarnings(false);/*w ww . j av a 2 s.c om*/ File file = new File("/usr/local/Output11.txt"); if (!file.exists()) { try { file.createNewFile(); FileWriter fw = new FileWriter(file.getAbsoluteFile(), true); BufferedWriter bw = new BufferedWriter(fw); bw.write("["); bw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } Authentication auth = new OAuth1(consumerKey, consumerSecret, token, secret); //Authentication auth = new com.twitter.hbc.httpclient.auth.BasicAuth(username, password); // Create a new BasicClient. By default gzip is enabled. BasicClient client = new ClientBuilder().name("sampleExampleClient").hosts(Constants.STREAM_HOST) .endpoint(endpoint).authentication(auth).processor(new StringDelimitedProcessor(queue)).build(); // Establish a connection client.connect(); // Do whatever needs to be done with messages for (int msgRead = 0; msgRead < 1000; msgRead++) { if (client.isDone()) { System.out.println("Client connection closed unexpectedly: " + client.getExitEvent().getMessage()); break; } String msg = queue.poll(5, TimeUnit.SECONDS); // String Time="time",Text="Text"; //Lang id; if (msg == null) { System.out.println("Did not receive a message in 5 seconds"); } else { System.out.println(msg); //System.out.println("**************hahahahahahahah********************"); try { FileWriter fw = new FileWriter(file.getAbsoluteFile(), true); BufferedWriter bw = new BufferedWriter(fw); if (msgRead == 999) bw.write(msg); else bw.write(msg + ","); bw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } /* JSONParser jsonParser = new JSONParser(); //JsonElement jsonElement = null; String key=""; try { //jsonElement= (JsonElement) jsonParser.parse(msg); JSONObject jsonObject = (JSONObject) jsonParser.parse(msg); //JsonObject jsonObjec = jsonElement.getAsJsonObject(); //for(Entry<String, JsonElement> entry : jsonObjec.entrySet()) // { key = entry.getKey(); // if(key=="delete") // System.out.println("this comment is deleted"); // } //JsonElement value = entry.getValue(); //***** printing date // Time = (String) jsonObject.get("created_at"); System.out.println("Date of creation====: " + jsonObject.get("created_at")); //******printing id // id = (Lang) jsonObject.get("id"); // System.out.println("id=========: " + jsonObject.get("id")); //*******text //Text = (String) jsonObject.get("text"); //System.out.println("Text==========: " + jsonObject.get("text")); //************inside user************ JSONObject structure = (JSONObject) jsonObject.get("user"); System.out.println("Into user structure , id====: " + structure.get("id")); System.out.println("Into user structure , name====: " + structure.get("name")); System.out.println("Into user structure , screen_name====: " + structure.get("screen_name")); System.out.println("Into user structure , location====: " + structure.get("location")); System.out.println("Into user structure , description====: " + structure.get("description")); System.out.println("Into user structure , followers====: " + structure.get("followers_count")); System.out.println("Into user structure , friends====: " + structure.get("friends_count")); System.out.println("Into user structure , listed====: " + structure.get("listed_count")); System.out.println("Into user structure , favorite====: " + structure.get("favorites_count")); System.out.println("Into user structure , status_count====: " + structure.get("status_count")); System.out.println("Into user structure , created at====: " + structure.get("created at")); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } */ } } FileWriter fw; try { fw = new FileWriter(file.getAbsoluteFile(), true); BufferedWriter bw = new BufferedWriter(fw); bw.write("]"); bw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } client.stop(); // Print some stats System.out.printf("The client read %d messages!\n", client.getStatsTracker().getNumMessages()); }
From source file:functionalTests.dataspaces.GCMFunctionalDataSpacesBase.java
private static void createInputFileContent(final File file) throws IOException { final File parentFile = file.getParentFile(); if (!parentFile.exists()) { assertTrue(parentFile.mkdirs()); }//from w ww.ja v a 2 s . c o m final BufferedWriter writer = new BufferedWriter(new FileWriter(file)); writer.write(INPUT_FILE_CONTENT); writer.close(); }
From source file:apm.generate.Generate.java
/** * /*from ww w. j a v a2 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); bufferedWriter.write(content); bufferedWriter.close(); fileWriter.close(); } else { //logger.info("??"); System.out.println("??"); } } catch (Exception e) { e.printStackTrace(); } }
From source file:ca.uqac.info.trace.conversion.TraceConverter.java
/** * Writes some string to a file/*from w ww . j a v a 2s .c o m*/ * @param filename The filename to write to * @param contents The file's contents */ private static void writeToFile(String filename, String contents) { try { // Create file FileWriter fstream = new FileWriter(filename); BufferedWriter out = new BufferedWriter(fstream); out.write(contents); //Close the output stream out.close(); } catch (Exception e) { // Catch exception if any System.err.println("ERROR: " + e.getMessage()); } }
From source file:gsn.http.ac.ParameterSet.java
private static void changeSensorName(String filepath, String name) { File f = new File(filepath); Pattern pat = Pattern.compile("name[\\s]*=[\\s]*\"[\\s]*[\\S]+[\\s]*\""); Matcher match;// ww w. jav a 2s . c om FileInputStream fs = null; InputStreamReader in = null; BufferedReader br = null; StringBuffer sb = new StringBuffer(); String textinLine; try { fs = new FileInputStream(f); in = new InputStreamReader(fs); br = new BufferedReader(in); while (true) { textinLine = br.readLine(); if (textinLine == null) break; if (textinLine.contains("<virtual-sensor")) { match = pat.matcher(textinLine); match.find(); textinLine = match.replaceFirst("name=\"" + name + "\""); } sb.append(textinLine + "\n"); } fs.close(); in.close(); br.close(); } catch (FileNotFoundException e) { logger.error(e.getMessage(), e); } catch (IOException e) { logger.error(e.getMessage(), e); } try { FileWriter fstream = new FileWriter(f); // write file again BufferedWriter outobj = new BufferedWriter(fstream); outobj.write(sb.toString()); outobj.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } }
From source file:com.book.jtm.chap03.HttpClientDemo.java
private static void writeParams(OutputStream output, List<NameValuePair> paramsList) throws IOException { StringBuilder paramStr = new StringBuilder(); for (NameValuePair pair : paramsList) { if (!TextUtils.isEmpty(paramStr)) { paramStr.append("&"); }//from w w w. j a v a 2s. c om paramStr.append(URLEncoder.encode(pair.getName(), "UTF-8")); paramStr.append("="); paramStr.append(URLEncoder.encode(pair.getValue(), "UTF-8")); } BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output, "UTF-8")); // ?? writer.write(paramStr.toString()); writer.flush(); writer.close(); }
From source file:Main.java
public static boolean writeTextContentToFile(String content, String dstPath) { BufferedWriter writer = null; try {// w w w . j ava 2s. com writer = new BufferedWriter(new FileWriter(dstPath)); writer.write(content); return true; } catch (IOException e) { e.printStackTrace(); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } } return false; }