public void getSavedLocations() { // System.out.println("inside getSavedLocations"); //CONSOLE * * * * * * * * * * * * * loc.clear(); // clear locations. helps refresh the list when reprinting all the locations BufferedWriter f = null; // just in case file has not been created yet BufferedReader br = null; try { // attempt to open the locations file if it doesn't exist, create it f = new BufferedWriter( new FileWriter("savedLocations.txt", true)); // evaluated true if file does not exist br = new BufferedReader(new FileReader("savedLocations.txt")); String line; // each line is one index of the list loc.add("Saved Locations"); // loop and read a line from the file as long as we don't get null while ((line = br.readLine()) != null) // add the read word to the wordList loc.add(line); } catch (IOException e) { e.printStackTrace(); } finally { try { // attempt the close the file br.close(); // close bufferedwriter } catch (IOException ex) { ex.printStackTrace(); } } }
// Load a neural network from memory public NeuralNetwork loadGenome() { // Read from disk using FileInputStream FileInputStream f_in = null; try { f_in = new FileInputStream("./memory/mydriver.mem"); } catch (FileNotFoundException e) { e.printStackTrace(); } // Read object using ObjectInputStream ObjectInputStream obj_in = null; try { obj_in = new ObjectInputStream(f_in); } catch (IOException e) { e.printStackTrace(); } // Read an object try { return (NeuralNetwork) obj_in.readObject(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return null; }
public void test_getContentsFolder() { try { Thread.sleep(2000); } catch (InterruptedException e1) { e1.printStackTrace(); } // Get the content HttpMethod get_col_contents = new GetMethod( SLING_URL + COLLECTION_URL + slug + "/" + CONTENTS_FOLDER + "/" + "sling:resourceType"); try { client.executeMethod(get_col_contents); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // handle response. String response_body = ""; try { response_body = get_col_contents.getResponseBodyAsString(); } catch (IOException e) { e.printStackTrace(); } assertEquals(response_body, CONTENTS_RESOURCE_TYPE); }
/** * 根据文件以byte[]形式返回文件的数据 * * @param file * @return */ public static byte[] getFileData(File file) { FileInputStream in = null; ByteArrayOutputStream out = null; try { in = new FileInputStream(file); out = new ByteArrayOutputStream(BUFFER_SIZE); int byteCount = 0; byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead = -1; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); byteCount += bytesRead; } out.flush(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (in != null) in.close(); if (out != null) out.close(); } catch (IOException ex) { ex.printStackTrace(); } } return out.toByteArray(); }
private static Directory index(Analyzer analyzer, String processingPath) { RAMDirectory directory = null; IndexWriter indexWriter = null; try { directory = new RAMDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_35, analyzer); indexWriter = new IndexWriter(directory, iwc); File file = new File(processingPath); index_h("", file, indexWriter); } catch (IOException e) { e.printStackTrace(); } finally { if (indexWriter != null) { try { indexWriter.close(); } catch (CorruptIndexException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } return directory; }
@RequestMapping(value = "/file/{id}", method = RequestMethod.GET) public void showFileContent(@PathVariable Long id, HttpServletResponse response) { UploadedFileDTO uploadedFileDTO = getUploadedFileService().findById(id); response.setContentType("application/pdf"); response.setHeader("Cache-Control", "private, max-age=5"); response.setHeader("Pragma", ""); byte[] file = uploadedFileDTO.getFile(); if (file.length > 0) { response.setContentLength(file.length); } InputStream inputStream = new ByteArrayInputStream(file); ServletOutputStream outputStream = null; try { outputStream = response.getOutputStream(); int b; while ((b = inputStream.read()) != -1) { outputStream.write(b); } } catch (IOException e) { e.printStackTrace(); } finally { try { outputStream.flush(); outputStream.close(); inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } }
// 添加一条记录 public static void addFile(String title, String content, Context context) { FileOutputStream fout = null; OutputStreamWriter writer = null; PrintWriter pw = null; try { fout = context.openFileOutput(title, context.MODE_PRIVATE); writer = new OutputStreamWriter(fout); pw = new PrintWriter(writer); pw.print(content); pw.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (pw != null) { pw.close(); } if (writer != null) { try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } if (fout != null) { try { fout.close(); } catch (IOException e) { e.printStackTrace(); } } } }
private String ReadWholeFileToString(String filename) { File file = new File(filename); StringBuffer contents = new StringBuffer(); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); String text = null; // repeat until all lines is read while ((text = reader.readLine()) != null) { contents.append(text).append(System.getProperty("line.separator")); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (reader != null) { reader.close(); } } catch (IOException e) { e.printStackTrace(); } } // show file contents here return contents.toString(); }
/** DOCUMENT ME! */ public void loadRaids() { File f = new File(REPO); if (!f.exists()) { return; } FileInputStream fIn = null; ObjectInputStream oIn = null; try { fIn = new FileInputStream(REPO); oIn = new ObjectInputStream(fIn); // de-serializing object raids = (HashMap<String, GregorianCalendar>) oIn.readObject(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { try { oIn.close(); fIn.close(); } catch (IOException e1) { e1.printStackTrace(); } } }
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { // 监听事件 // TODO add your handling code here: if (jRadioButton1.isSelected()) { jRadioButtonName = jRadioButton1.getText(); } else if (jRadioButton2.isSelected()) { jRadioButtonName = jRadioButton2.getText(); } try { fwriter = new FileWriter(filename); fwriter.write(jTextField1.getText()); fwriter.write("\r\n"); fwriter.write(jTextField2.getText()); fwriter.write("\r\n"); fwriter.write(jTextField3.getText()); fwriter.write("\r\n"); fwriter.write(jTextField4.getText()); fwriter.write("\r\n"); fwriter.write(jRadioButtonName); fwriter.write("\r\n"); } catch (IOException e) { e.printStackTrace(); } finally { try { fwriter.flush(); fwriter.close(); } catch (IOException e) { e.printStackTrace(); } } this.dispose(); }
public static void writeToFileByURL(String urlAddress, String fileAddres) { // String urlAddress = "http://www.mkyoung.com"; // String fileAddres = "test.html"; URL url; BufferedReader br = null; BufferedWriter bw = null; try { url = new URL(urlAddress); URLConnection conn = url.openConnection(); br = new BufferedReader(new InputStreamReader(conn.getInputStream())); File file = new File(fileAddres); String inputLine; bw = new BufferedWriter(new FileWriter(file)); while ((inputLine = br.readLine()) != null) { bw.write(inputLine); } System.out.println("Done"); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { bw.flush(); bw.close(); br.close(); } catch (IOException e) { e.printStackTrace(); } } }
public boolean getCaptchaImgAndCookies(int times) { captchaCookies.clear(); if (times > maxRecursiveTimes) return false; Connection con = JsoupUtil.getResourceCon( "https://www.zhihu.com/captcha.gif?r=" + System.currentTimeMillis() + "&type=login"); Response rs = null; try { rs = con.execute(); } catch (IOException e) { e.printStackTrace(); log.info("获取验证码第" + times + "次失败"); return getCaptchaImgAndCookies(++times); } File file = new File(EzraPoundUtil.CAPTCHA_DIR); try { FileOutputStream out = (new FileOutputStream(file)); out.write(rs.bodyAsBytes()); } catch (IOException e) { e.printStackTrace(); } captchaCookies.putAll(rs.cookies()); log.info("验证码已保存" + ",路径为:" + file.getAbsolutePath()); log.info("验证码对应cookie为:" + captchaCookies); return true; }
protected void initializeTasks() { // read the file line by line and create Node to insert in dll BufferedReader br = null; try { br = new BufferedReader(new FileReader(storageFile)); String line = br.readLine(); StringBuilder stringBuilder = null; while (line != null) { stringBuilder = new StringBuilder(); Node tNode = new Node(String.valueOf(line)); nodeList.add(tNode); stringBuilder.append(Integer.getInteger(line)); stringBuilder.append('\n'); line = br.readLine(); } if (stringBuilder != null) { FileUtil.writeFile(stringBuilder.toString().getBytes(), storageFile.getPath()); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null) br.close(); } catch (IOException e) { e .printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } } }
// function to do the join use case public static void share() throws Exception { HttpPost method = new HttpPost(url + "/share"); String ipAddress = null; Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); while (en.hasMoreElements()) { NetworkInterface ni = (NetworkInterface) en.nextElement(); if (ni.getName().equals("eth0")) { Enumeration<InetAddress> en2 = ni.getInetAddresses(); while (en2.hasMoreElements()) { InetAddress ip = (InetAddress) en2.nextElement(); if (ip instanceof Inet4Address) { ipAddress = ip.getHostAddress(); break; } } break; } } method.setEntity(new StringEntity(username + ';' + ipAddress, "UTF-8")); try { ResponseHandler<String> responseHandler = new BasicResponseHandler(); connIp = client.execute(method, responseHandler); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } // get present time date = new Date(); long start = date.getTime(); // Execute the vishwa share process Process p = Runtime.getRuntime().exec("java -jar vishwa/JVishwa.jar " + connIp); String ch = "alive"; System.out.println("Type kill to unjoin from the grid"); while (!ch.equals("kill")) { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); ch = in.readLine(); } p.destroy(); date = new Date(); long end = date.getTime(); long durationInt = end - start; String duration = String.valueOf(durationInt); method = new HttpPost(url + "/shareAck"); method.setEntity(new StringEntity(username + ";" + duration, "UTF-8")); try { client.execute(method); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } }
public void run() { try { File f2 = new File(MATCH_LOG_FILE); if (f2.exists() && !f2.isDirectory()) { matchReader = new BufferedReader(new FileReader(MATCH_LOG_FILE)); String sCurrentLine; for (int i = 0; i < logCount; i++) { matchReader.readLine(); } while ((sCurrentLine = matchReader.readLine()) != null) { if (sendToBackOffice(sCurrentLine)) { System.out.println("Updating log count"); logWriter = new PrintWriter(new FileWriter("c:\\temp\\countBackOffice.log")); logWriter.print(++logCount); logWriter.close(); } } } } catch (IOException e) { e.printStackTrace(); } finally { try { if (matchReader != null) matchReader.close(); } catch (IOException ex) { ex.printStackTrace(); } } }
@Override public boolean writeData(String uri, byte[] data) { /* * Delete the parent folder if the parent folder exists * */ File f = new File(uri); if (f.getName().equals(storageConfiguration.getProperty("postfix"))) { f = f.getParentFile(); Path file = new Path(String.valueOf(f)); try { if (fileSystem.exists(file)) { fileSystem.delete(file, true); } } catch (IOException e) { e.printStackTrace(); } } SequenceFile.Writer writer = getWriterFor(uri); HDFSByteChunk byteChunk = new HDFSByteChunk(data, uri); try { writer.append(new IntWritable(0), byteChunk); writer.close(); } catch (IOException e) { e.printStackTrace(); return false; } return true; }
public static void writeCentroidsToFile(HashMap<Integer, Cluster> clusterList) { File file = new File(Main.FILE_PATH + "centroids.txt"); BufferedWriter w = null; try { w = new BufferedWriter(new FileWriter(file)); for (int i = 0; i < clusterList.size(); i++) { String line = ""; ArrayList<Double> centroid = clusterList.get(i + 1).getCentroid(); for (int j = 0; j < centroid.size() - 1; j++) { line += centroid.get(j) + "\t"; } line += centroid.get(centroid.size() - 1); w.write(line + "\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { w.close(); } catch (IOException e) { e.printStackTrace(); } } }
/* @Test public void searchContentTest() throws IOException { System.out.println("Search"); textbuddy.searchContent("textfile.txt"); }*/ public boolean testIfFilesAreTheSame(File file1, File file2) { BufferedReader file1Reader = null; BufferedReader file2Reader = null; boolean equals = true; ; try { file1Reader = new BufferedReader(new FileReader(file1)); file2Reader = new BufferedReader(new FileReader(file2)); String linefromfile1; String linefromfile2; while (((linefromfile1 = file1Reader.readLine()) != null) && ((linefromfile2 = file2Reader.readLine()) != null)) { if (!linefromfile1.equals(linefromfile2)) { equals = false; break; } } } catch (IOException e) { e.printStackTrace(); } finally { try { file1Reader.close(); file2Reader.close(); } catch (IOException e) { e.printStackTrace(); } } return equals; }
/** * @param src 源文件 * @param dst 目标位置 */ private static void copy(File src, File dst) { InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE); out = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE); byte[] buffer = new byte[BUFFER_SIZE]; int len = 0; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } } catch (Exception e) { e.printStackTrace(); } finally { if (null != in) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != out) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } }
private String ask(String cmd) { BufferedWriter out = null; BufferedReader in = null; Socket sock = null; String ret = ""; try { System.out.println(server); sock = new Socket(server, ServerListener.PORT); out = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream())); out.write(cmd, 0, cmd.length()); out.flush(); in = new BufferedReader(new InputStreamReader(sock.getInputStream())); int inr = in.read(); while (inr != ';') { ret += Character.toString((char) inr); inr = in.read(); } } catch (IOException io) { io.printStackTrace(); } finally { try { out.close(); in.close(); sock.close(); } catch (IOException io) { io.printStackTrace(); } } return ret; }
/** * Save onscreen image to file - suffix must be png, jpg, or gif. * * @param filename the name of the file with one of the required suffixes */ public static void save(String filename) { File file = new File(filename); String suffix = filename.substring(filename.lastIndexOf('.') + 1); // png files if (suffix.toLowerCase().equals("png")) { try { ImageIO.write(onscreenImage, suffix, file); } catch (IOException e) { e.printStackTrace(); } } // need to change from ARGB to RGB for jpeg // reference: // http://archives.java.sun.com/cgi-bin/wa?A2=ind0404&L=java2d-interest&D=0&P=2727 else if (suffix.toLowerCase().equals("jpg")) { WritableRaster raster = onscreenImage.getRaster(); WritableRaster newRaster; newRaster = raster.createWritableChild(0, 0, width, height, 0, 0, new int[] {0, 1, 2}); DirectColorModel cm = (DirectColorModel) onscreenImage.getColorModel(); DirectColorModel newCM = new DirectColorModel( cm.getPixelSize(), cm.getRedMask(), cm.getGreenMask(), cm.getBlueMask()); BufferedImage rgbBuffer = new BufferedImage(newCM, newRaster, false, null); try { ImageIO.write(rgbBuffer, suffix, file); } catch (IOException e) { e.printStackTrace(); } } else { System.out.println("Invalid image file type: " + suffix); } }
public void testSerial() { assertTrue(_nbhm.isEmpty()); final String k1 = "k1"; final String k2 = "k2"; assertThat(_nbhm.put(k1, "v1"), nullValue()); assertThat(_nbhm.put(k2, "v2"), nullValue()); // Serialize it out try { FileOutputStream fos = new FileOutputStream("NBHM_test.txt"); ObjectOutputStream out = new ObjectOutputStream(fos); out.writeObject(_nbhm); out.close(); } catch (IOException ex) { ex.printStackTrace(); } // Read it back try { File f = new File("NBHM_test.txt"); FileInputStream fis = new FileInputStream(f); ObjectInputStream in = new ObjectInputStream(fis); NonBlockingIdentityHashMap nbhm = (NonBlockingIdentityHashMap) in.readObject(); in.close(); assertThat( "serialization works", nbhm.toString(), anyOf(is("{k1=v1, k2=v2}"), is("{k2=v2, k1=v1}"))); if (!f.delete()) throw new IOException("delete failed"); } catch (IOException ex) { ex.printStackTrace(); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } }
/** * write categories to AIMLIF file * * @param cats array list of categories * @param filename AIMLIF filename */ public void writeIFCategories(ArrayList<Category> cats, String filename) { // System.out.println("writeIFCategories "+filename); BufferedWriter bw = null; File existsPath = new File(aimlif_path); if (existsPath.exists()) try { // Construct the bw object bw = new BufferedWriter(new FileWriter(aimlif_path + "/" + filename)); for (Category category : cats) { bw.write(Category.categoryToIF(category)); bw.newLine(); } } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } finally { // Close the bw try { if (bw != null) { bw.flush(); bw.close(); } } catch (IOException ex) { ex.printStackTrace(); } } }
private void saveTab(String toSave, File f) { boolean ok = false; BufferedWriter out = null; try { ok = f.createNewFile(); } catch (IOException e) { e.printStackTrace(); } if (ok) { try { out = new BufferedWriter(new FileWriter(f)); out.write(toSave); } catch (IOException e1) { e1.printStackTrace(); } finally { try { out.close(); } catch (IOException e2) { e2.printStackTrace(); } } } else { System.out.println("Couldnt create file..."); } // } }
/** * Take the name of a jar file and extract the plugin.xml file, if possible, to a temporary file. * * @param f The jar file to extract from. * @return a temporary file to which the plugin.xml file has been copied. */ public static File unpackPluginXML(File f) { InputStream in = null; OutputStream out = null; try { JarFile jar = new JarFile(f); ZipEntry entry = jar.getEntry(PLUGIN_XML_FILE); if (entry == null) { return null; } File dest = File.createTempFile("jabref_plugin", ".xml"); dest.deleteOnExit(); in = new BufferedInputStream(jar.getInputStream(entry)); out = new BufferedOutputStream(new FileOutputStream(dest)); byte[] buffer = new byte[2048]; for (; ; ) { int nBytes = in.read(buffer); if (nBytes <= 0) break; out.write(buffer, 0, nBytes); } out.flush(); return dest; } catch (IOException ex) { ex.printStackTrace(); return null; } finally { try { if (out != null) out.close(); if (in != null) in.close(); } catch (IOException ex) { ex.printStackTrace(); } } }
private void loadLang() { File lang = new File(getDataFolder(), "lang.yml"); OutputStream out = null; InputStream defLangStream = this.getResource("lang.yml"); if (!lang.exists()) { try { getDataFolder().mkdir(); lang.createNewFile(); if (defLangStream != null) { out = new FileOutputStream(lang); int read; byte[] bytes = new byte[1024]; while ((read = defLangStream.read(bytes)) != -1) { out.write(bytes, 0, read); } YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(defLangStream); Lang.setFile(defConfig); return; } } catch (IOException e) { e.printStackTrace(); // So they notice getLogger().severe("[PlayerVaults] Couldn't create language file."); getLogger().severe("[PlayerVaults] This is a fatal error. Now disabling"); this.setEnabled(false); // Without it loaded, we can't send them messages } finally { if (defLangStream != null) { try { defLangStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } } YamlConfiguration conf = YamlConfiguration.loadConfiguration(lang); for (Lang item : Lang.values()) { if (conf.getString(item.getPath()) == null) { conf.set(item.getPath(), item.getDefault()); } } Lang.setFile(conf); try { conf.save(lang); } catch (IOException e) { getLogger().log(Level.WARNING, "PlayerVaults: Failed to save lang.yml."); getLogger() .log(Level.WARNING, "PlayerVaults: Report this stack trace to drtshock and gomeow."); e.printStackTrace(); } }
public static Map<String, String> readProperties(InputStream inputStream) { Map<String, String> propertiesMap = null; try { propertiesMap = new LinkedHashMap<String, String>(); Properties properties = new Properties(); properties.load(inputStream); Enumeration<?> enumeration = properties.propertyNames(); while (enumeration.hasMoreElements()) { String key = (String) enumeration.nextElement(); String value = (String) properties.get(key); propertiesMap.put(key, value); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return propertiesMap; }
public static void main(String[] args) { // TODO Auto-generated method stub File file = new File("Exp6_Gis.txt"); BufferedReader reader = null; String tempString = null; int line = 1; try { System.out.println("以行为单位读取文件内容,一次读一整行:"); reader = new BufferedReader(new FileReader(file)); while ((tempString = reader.readLine()) != null) { System.out.println("Line" + line + ":" + tempString); line++; } reader.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
public void test_getTagsFolder() { try { Thread.sleep(2000); } catch (InterruptedException e1) { e1.printStackTrace(); } String response_body = ""; HttpMethod get_col_tags = new GetMethod( SLING_URL + COLLECTION_URL + slug + "/" + TAGS_FOLDER + "/" + "sling:resourceType"); try { client.executeMethod(get_col_tags); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { response_body = get_col_tags.getResponseBodyAsString(); } catch (IOException e) { e.printStackTrace(); } assertEquals(response_body, TAGS_RESOURCE_TYPE); get_col_tags.releaseConnection(); }
@Override public void run() { if (action.equals("s")) { Socket send = null; while (send == null) { try { System.out.println("wait"); send = server.accept(); } catch (IOException e) { e.printStackTrace(); } } sendFile(file, send); } if (action.equals("r")) { Socket recive = null; try { recive = new Socket(host, onPort); } catch (IOException e) { e.printStackTrace(); } receiveFile(reciveFile, recive); try { recive.close(); } catch (IOException e) { e.printStackTrace(); } } }