List of usage examples for java.io FileReader close
public void close() throws IOException
From source file:cerrla.Performance.java
/** * Reads a raw numerical performance file and stores the values as * accessible private values.//from w w w . j av a 2 s . c o m * * @param perfFile * The performance file to read. * @return True if the file was read successfully, false otherwise. */ public static boolean readRawPerformanceFile(File perfFile, boolean byEpisode) throws Exception { if (Config.getInstance().getGeneratorFile() == null) { // First, read the last line of the normal file for the time RandomAccessFile raf = new RandomAccessFile(perfFile, "r"); long pos = perfFile.length() - 1; StringBuffer line = new StringBuffer(); char c; boolean foundIt = false; do { raf.seek(pos); c = (char) raf.read(); foundIt |= Character.isDigit(c); line.append(c); pos--; } while (!foundIt || Character.isDigit(c) || c == ':'); raf.close(); String time = line.reverse().toString().trim(); String[] timeSplit = time.split(":"); runTime_ = (Long.parseLong(timeSplit[2]) + 60 * Long.parseLong(timeSplit[1]) + 3600 * Long.parseLong(timeSplit[0])) * 1000; } if (Config.getInstance().getGeneratorFile() == null) perfFile = new File(perfFile.getPath() + "raw"); else perfFile = new File(perfFile.getPath() + "greedy"); performanceMap_ = new TreeMap<Integer, Float[]>(); FileReader reader = new FileReader(perfFile); BufferedReader buf = new BufferedReader(reader); // For every value within the performance file String input = null; Float[] prevPerfs = null; while ((input = buf.readLine()) != null) { String[] vals = input.split("\t"); if (vals[PerformanceDetails.EPISODE.ordinal()].equals("Episode")) continue; Float[] perfs = new Float[PerformanceDetails.values().length]; int episode = 0; for (PerformanceDetails detail : PerformanceDetails.values()) { if (vals.length > detail.ordinal()) { if (!vals[detail.ordinal()].equals("null")) perfs[detail.ordinal()] = Float.parseFloat(vals[detail.ordinal()]); else if (detail.equals(PerformanceDetails.ELITEMEAN) && !vals[PerformanceDetails.ELITEMAX.ordinal()].equals("null")) perfs[detail.ordinal()] = Float.parseFloat(vals[PerformanceDetails.ELITEMAX.ordinal()]); else if (detail.equals(PerformanceDetails.ELITEMEAN) || detail.equals(PerformanceDetails.ELITEMAX)) perfs[detail.ordinal()] = Float.parseFloat(vals[PerformanceDetails.MEAN.ordinal()]); else if (prevPerfs != null) perfs[detail.ordinal()] = prevPerfs[detail.ordinal()]; } if (detail.equals(PerformanceDetails.EPISODE)) episode = perfs[detail.ordinal()].intValue(); } performanceMap_.put(episode, perfs); prevPerfs = perfs; } buf.close(); reader.close(); return true; }
From source file:org.apache.hadoop.mapred.util.LinuxResourceCalculatorPlugin.java
/** * Read /proc/stat file, parse and calculate cumulative CPU *//* w w w .ja v a 2s.c o m*/ private void readProcStatFile() { // Read "/proc/stat" file BufferedReader in = null; FileReader fReader = null; try { fReader = new FileReader(procfsStatFile); in = new BufferedReader(fReader); } catch (FileNotFoundException f) { // shouldn't happen.... return; } Matcher mat = null; try { String str = in.readLine(); while (str != null) { mat = CPU_TIME_FORMAT.matcher(str); if (mat.find()) { long uTime = Long.parseLong(mat.group(1)); long nTime = Long.parseLong(mat.group(2)); long sTime = Long.parseLong(mat.group(3)); cumulativeCpuTime = uTime + nTime + sTime; // milliseconds break; } str = in.readLine(); } cumulativeCpuTime *= jiffyLengthInMillis; } catch (IOException io) { // LOG.warn("Error reading the stream " + io); } finally { // Close the streams try { fReader.close(); try { in.close(); } catch (IOException i) { LOG.warn("Error closing the stream " + in); } } catch (IOException i) { LOG.warn("Error closing the stream " + fReader); } } }
From source file:com.github.hexosse.memworth.WorthBuilder.java
/** * Parse the csv file/*from ww w .j a va 2s. c o m*/ * * @return WorthBuilder */ public WorthBuilder parse() { try { // Free list of items items.clear(); // Load csv file into file reader FileReader reader = new FileReader(csvFile); // parse csv file using specified file format for (CSVRecord record : csvFormat.parse(reader)) { // Skip empty lines if (record.get(0).isEmpty()) continue; // Skip title if (record.get(0).equals("ID")) continue; // Skip item without price if (record.get(3).isEmpty()) continue; if (record.get(4).isEmpty()) continue; // Create Item String[] idData = record.get(0).replaceAll("[^0-9]", " ").trim().split(" "); int id = Integer.parseInt(idData[0]); int data = Integer.parseInt(idData.length > 1 ? idData[1] : "0"); String comment = record.get(1); String sworth = record.get(4).trim().replaceAll(" ", "") .replaceAll("^[^a-zA-Z0-9\\s]+|[^a-zA-Z0-9\\s]+$", ""); Number worth = numFormat.parse(sworth); // Add Item to list if (worth.doubleValue() != 0) items.add(new Item(id, data, comment, worth.doubleValue())); } // Close csv file reader.close(); // Sort the item list Collections.sort(items); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } return this; }
From source file:com.oneis.javascript.Runtime.java
/** * Load a script into the runtime// www . j a v a 2 s .com */ public void loadScript(String scriptPathname, String givenFilename, String prefix, String suffix) throws java.io.IOException { checkContext(); FileReader script = new FileReader(scriptPathname); try { if (prefix != null || suffix != null) { // TODO: Is it worth loading JS files with prefix+suffix using a fancy Reader which concatenates other readers? StringBuilder builder = new StringBuilder(); if (prefix != null) { builder.append(prefix); } builder.append(IOUtils.toString(script)); if (suffix != null) { builder.append(suffix); } currentContext.evaluateString(runtimeScope, builder.toString(), givenFilename, 1, null /* no security domain */); } else { currentContext.evaluateReader(runtimeScope, script, givenFilename, 1, null /* no security domain */); } } finally { script.close(); } }
From source file:com.wavemaker.tools.data.ImportDB.java
private void setValuesFromRevEngFilesIfNotSet() { if (this.packageName != null) { return;// ww w . j a va2 s .c o m } boolean packageSet = false; boolean tableFilterSet = false; boolean schemaFilterSet = false; for (File f : this.revengFiles) { try { FileReader reader = new FileReader(f); Reveng r = Reveng.load(reader); if (r.getPackage() != null && !packageSet) { setPackage(r.getPackage()); this.valuesFromReveng = true; packageSet = true; } if (r.getTableFilters() != null && !tableFilterSet) { setTableFilters(r.getTableFilters()); this.valuesFromReveng = true; tableFilterSet = true; } if (r.getSchemaFilters() != null && !schemaFilterSet) { setSchemaFilters(r.getSchemaFilters()); this.valuesFromReveng = true; schemaFilterSet = true; } reader.close(); } catch (IOException ignore) { } } }
From source file:com.knowgate.dfs.FileSystem.java
/** * <p>Read a text file and returns a character array with it</p> * Enconding is UTF-8 by default// w w w . j av a2 s . c o m * @param sFilePath Full path of file to be readed. Like "file:///tmp/myfile.txt" or "ftp://myhost:21/dir/myfile.txt" * @return character array with full contents of file * @throws FileNotFoundException * @throws IOException * @throws OutOfMemoryError * @throws FTPException */ public static char[] readfile(String sFilePath) throws FileNotFoundException, IOException, OutOfMemoryError, FTPException { if (DebugFile.trace) { DebugFile.writeln("Begin FileSystem.readfile(" + sFilePath + ")"); DebugFile.incIdent(); } char[] aBuffer; String sLower = sFilePath.toLowerCase(); if (sLower.startsWith("file://")) sFilePath = sFilePath.substring(7); if (sLower.startsWith("http://") || sLower.startsWith("https://") || sLower.startsWith("ftp://")) { aBuffer = new FileSystem().readfilestr(sFilePath, "UTF-8").toCharArray(); } else { File oFile = new File(sFilePath); aBuffer = new char[(int) oFile.length()]; FileReader oReader = new FileReader(oFile); oReader.read(aBuffer); oReader.close(); oReader = null; oFile = null; } if (DebugFile.trace) { DebugFile.decIdent(); DebugFile.writeln("End FileSystem.readfile() : " + String.valueOf(aBuffer.length)); } return aBuffer; }
From source file:mtmo.test.mediadrm.MainActivity.java
private boolean readPropFromFile() { boolean ret = false; FileReader fr = null; BufferedReader br = null;/*from w w w . j a v a 2s. com*/ try { fr = new FileReader(Constants.PROPERTY_FILE_PATH); br = new BufferedReader(fr); String line; for (int i = 0; (line = br.readLine()) != null; i++) { switch (i) { case 0: mServiceId = line; break; case 1: mAccountId = line; break; default: } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null) br.close(); if (fr != null) fr.close(); ret = true; } catch (IOException e) { e.printStackTrace(); } } return ret; }
From source file:gov.nasa.jpl.xdata.nba.impoexpo.manager.NBAManager.java
@Override public void aquire(String parseType, Object input) { try {/*from ww w . ja v a2s . c om*/ // Read given JSON file LOG.info("Parsing file:" + input); FileReader reader = new FileReader((String) input); // Pare with JSON simple parser JSONParser jsonParser = new JSONParser(); JSONObject jsonObject = (JSONObject) jsonParser.parse(reader); JSONArray result = (JSONArray) jsonObject.get("resultSets"); JSONObject jObj = (JSONObject) result.get(0); JSONArray rows = (JSONArray) jObj.get("rowset"); String[] inputlist = input.toString().split("/"); String filename = inputlist[inputlist.length - 1]; String gameId = filename.substring(0, filename.indexOf('_')); if (parseType.equalsIgnoreCase("parseComments")) { long comments = 0; LOG.info("finished parsing file. Total number of comments:" + comments); } else if (parseType.equalsIgnoreCase("parseGamePlayers")) { long players = 0; for (int i = 0; i < rows.size(); i++) { // Store the gamePlayers with key id == gameId_playerId GamePlayer gpGamePlayer = parseGamePlayer(gameId, (JSONArray) rows.get(i)); storeGamePlayers(gpGamePlayer.getId(), gpGamePlayer); ++players; } reader.close(); LOG.info("finished parsing file. Total number of players:" + players); } else if (parseType.equalsIgnoreCase("parseGamestats")) { long stats = 0; LOG.info("finished parsing file. Total number of game stats:" + stats); } else if (parseType.equalsIgnoreCase("parseNotebook")) { long notebook = 0; LOG.info("finished parsing file. Total number of game stats:" + notebook); } else if (parseType.equalsIgnoreCase("parsePlayByPlay")) { long plays = 0; LOG.info("finished parsing file. Total number of game stats:" + plays); } else if (parseType.equalsIgnoreCase("parsePreview")) { long preview = 0; LOG.info("finished parsing file. Total number of game stats:" + preview); } else if (parseType.equalsIgnoreCase("parseRecap")) { long recaps = 0; LOG.info("finished parsing file. Total number of game stats:" + recaps); } } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } catch (ParseException ex) { ex.printStackTrace(); } catch (NullPointerException ex) { ex.printStackTrace(); } }
From source file:com.freedomotic.plugins.TrackingReadFile.java
/** * Reads room names from file./*from w w w. ja va 2s .com*/ * * @param f file of room names */ private void readMoteFileRooms(File f) { FileReader fr = null; ArrayList<Coordinate> coord = new ArrayList<Coordinate>(); String userId = FilenameUtils.removeExtension(f.getName()); try { LOG.info("Reading coordinates from file {}", f.getAbsolutePath()); fr = new FileReader(f); BufferedReader br = new BufferedReader(fr); String line; while ((line = br.readLine()) != null) { //tokenize string StringTokenizer st = new StringTokenizer(line, ","); String roomName = st.nextToken(); LOG.info("Mote {} coordinate added {}", userId, line); ZoneLogic zone = environmentRepository.findAll().get(0).getZone(roomName); if (!(zone == null)) { FreedomPoint roomCenterCoordinate = getPolygonCenter(zone.getPojo().getShape()); Coordinate c = new Coordinate(); c.setUserId(userId); c.setX(roomCenterCoordinate.getX()); c.setY(roomCenterCoordinate.getY()); c.setTime(new Integer(st.nextToken())); coord.add(c); } else { LOG.warn("Room '{}' not found.", roomName); } } fr.close(); WorkerThread wt = new WorkerThread(this, coord, ITERATIONS); workers.add(wt); } catch (FileNotFoundException ex) { LOG.error("Coordinates file not found for mote " + userId); } catch (IOException ex) { LOG.error("IOException: ", ex); } finally { try { fr.close(); } catch (IOException ex) { LOG.error("IOException: ", ex); } } }