private void compare(final File actualFile, final File expectedFile) throws IOException { LineNumberReader actualReader = null; LineNumberReader expectedReader = null; try { actualReader = new LineNumberReader(new FileReader(actualFile)); expectedReader = new LineNumberReader(new FileReader(expectedFile)); String actualLine = actualReader.readLine(); String expectedLine = expectedReader.readLine(); while (actualLine != null && expectedLine != null) { assertEquals( actualFile.getPath() + ":" + actualReader.getLineNumber() + " unexpected line", expectedLine, actualLine); actualLine = actualReader.readLine(); expectedLine = expectedReader.readLine(); } if (expectedLine != null) { fail(actualFile.getPath() + ":" + actualReader.getLineNumber() + " Too many line in file"); } if (actualLine != null) { fail( actualFile.getPath() + ":" + actualReader.getLineNumber() + " not enough line in file"); } } finally { if (actualReader != null) actualReader.close(); if (expectedReader != null) expectedReader.close(); } }
private void determineNameMapping(JarFile paramJarFile, Set paramSet, Map paramMap) throws IOException { InputStream localInputStream = paramJarFile.getInputStream(paramJarFile.getEntry("META-INF/INDEX.JD")); if (localInputStream == null) handleException("jardiff.error.noindex", null); LineNumberReader localLineNumberReader = new LineNumberReader(new InputStreamReader(localInputStream, "UTF-8")); String str = localLineNumberReader.readLine(); if ((str == null) || (!str.equals("version 1.0"))) handleException("jardiff.error.badheader", str); while ((str = localLineNumberReader.readLine()) != null) { List localList; if (str.startsWith("remove")) { localList = getSubpaths(str.substring("remove".length())); if (localList.size() != 1) handleException("jardiff.error.badremove", str); paramSet.add(localList.get(0)); continue; } if (str.startsWith("move")) { localList = getSubpaths(str.substring("move".length())); if (localList.size() != 2) handleException("jardiff.error.badmove", str); if (paramMap.put(localList.get(1), localList.get(0)) != null) handleException("jardiff.error.badmove", str); continue; } if (str.length() <= 0) continue; handleException("jardiff.error.badcommand", str); } localLineNumberReader.close(); localInputStream.close(); }
private ArrayList<String> readLines(File todoFile) { ArrayList<String> lines = new ArrayList<String>(); LineNumberReader reader = null; if (todoFile.exists()) { try { reader = new LineNumberReader(new BufferedReader(new FileReader(todoFile))); String line = null; while ((line = reader.readLine()) != null) { lines.add(line); } } catch (FileNotFoundException e) { Logger logger = Logger.getLogger(getPackageName()); logger.log(Level.SEVERE, "Unable to read items from todo.txt", e); } catch (IOException e) { Logger logger = Logger.getLogger(getPackageName()); logger.log(Level.SEVERE, "Unable to read items from todo.txt", e); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { Logger logger = Logger.getLogger(getPackageName()); logger.log(Level.SEVERE, "Unable to close todo.txt", e); } } } } return lines; }
/** * This will return an ArrayList of the class Mount. The class mount contains the following * property's: device mountPoint type flags * * <p>These will provide you with any information you need to work with the mount points. * * @return <code>ArrayList<Mount></code> an ArrayList of the class Mount. * @throws Exception if we cannot return the mount points. */ protected static ArrayList<Mount> getMounts() throws Exception { final String tempFile = "/data/local/RootToolsMounts"; // copy /proc/mounts to tempfile. Directly reading it does not work on 4.3 Shell shell = Shell.startRootShell(); Toolbox tb = new Toolbox(shell); tb.copyFile("/proc/mounts", tempFile, false, false); tb.setFilePermissions(tempFile, "777"); shell.close(); LineNumberReader lnr = null; lnr = new LineNumberReader(new FileReader(tempFile)); String line; ArrayList<Mount> mounts = new ArrayList<Mount>(); while ((line = lnr.readLine()) != null) { Log.d(RootCommands.TAG, line); String[] fields = line.split(" "); mounts.add( new Mount( new File(fields[0]), // device new File(fields[1]), // mountPoint fields[2], // fstype fields[3] // flags )); } lnr.close(); return mounts; }
/** * Convert the given Class to an HTML. * * @param configuration the configuration. * @param cd the class to convert. * @param outputdir the name of the directory to output to. */ public static void convertClass(Configuration configuration, ClassDoc cd, String outputdir) { if (cd == null || outputdir == null) { return; } File file; SourcePosition sp = cd.position(); if (sp == null || (file = sp.file()) == null) { return; } try { int lineno = 1; String line; StringBuffer output = new StringBuffer(); LineNumberReader reader = new LineNumberReader(new FileReader(file)); try { while ((line = reader.readLine()) != null) { output.append(formatLine(line, configuration.sourcetab, lineno)); lineno++; } } finally { reader.close(); } output = addLineNumbers(output.toString()); output.insert(0, getHeader()); output.append(getFooter()); writeToFile(output.toString(), outputdir, cd.name(), configuration); } catch (Exception e) { e.printStackTrace(); } }
public static Set<String> retrievePeptides(File peptideFastaFile) { BufferedReader reader; Set<String> peptideSet = new TreeSet<String>(); try { LineNumberReader lnr = new LineNumberReader(new FileReader(peptideFastaFile)); lnr.skip(Long.MAX_VALUE); int nLines = lnr.getLineNumber(); System.out.println(nLines); lnr.close(); reader = new BufferedReader(new FileReader(peptideFastaFile)); String nextLine; int lineCounter = 0; while ((nextLine = reader.readLine()) != null) { if (nextLine.length() > 0 && nextLine.charAt(0) != '>') { peptideSet.add(nextLine); } if (lineCounter % 1000000 == 0) { System.out.println(lineCounter + "/" + nLines); } lineCounter++; } reader.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return peptideSet; }
private void test(String path) throws IOException { int count = 0; int ok = 0; int errors = 0; LineNumberReader lr = new LineNumberReader(new InputStreamReader(getClass().getResourceAsStream(path), "UTF-8")); String line; while ((line = lr.readLine()) != null) { if (line.trim().length() > 0 && !line.startsWith("#")) { try { int pos = line.indexOf('|'); if (pos > 0) { validate(line.substring(0, pos), line.substring(pos + 1)); } else { validate(line); } ok++; } catch (Exception e) { logger.warn(e.getMessage()); errors++; } count++; } } lr.close(); assertEquals(errors, 0); assertEquals(ok, count); }
public void open() throws IOException { paneCenter.getChildren().clear(); String station = (String) cbStations.getValue(); File f = new File("database\\" + station + "\\status.txt"); FileReader fr1 = new FileReader(f); LineNumberReader ln = new LineNumberReader(fr1); int count = 0; while (ln.readLine() != null) { count++; } ln.close(); fr1.close(); FileReader fr2 = new FileReader(f); BufferedReader br = new BufferedReader(fr2); paneCenter.add(new Label("Last seen : " + (br.readLine())), 0, 0); for (int i = 1; i < count; i++) { paneCenter.add(new Label(br.readLine()), 0, i); } br.close(); fr2.close(); addQuantityToCB(); }
public static String DNS(int n, boolean format) { String dns = null; Process process = null; LineNumberReader reader = null; try { final String CMD = "getprop net.dns" + (n <= 1 ? 1 : 2); process = Runtime.getRuntime().exec(CMD); reader = new LineNumberReader(new InputStreamReader(process.getInputStream())); String line = null; while ((line = reader.readLine()) != null) { dns = line.trim(); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (reader != null) reader.close(); if (process != null) process.destroy(); // 测试发现,可能会抛异常 } catch (IOException e) { e.printStackTrace(); } } return format ? (dns != null ? dns.replace('.', '_') : dns) : dns; }
private static List<Mount> getMounts() { LineNumberReader lnr = null; try { lnr = new LineNumberReader(new FileReader(MOUNT_FILE)); } catch (FileNotFoundException e1) { e1.printStackTrace(); return null; } String line; ArrayList<Mount> mounts = new ArrayList<Mount>(); try { while ((line = lnr.readLine()) != null) { String[] fields = line.split(" "); mounts.add(new Mount(new File(fields[0]), new File(fields[1]), fields[2], fields[3])); } lnr.close(); } catch (IOException e) { e.printStackTrace(); } return mounts; }
protected int countRows(RetailerSite retailerSite, DataFile dataFile) { File filePath = null; try { filePath = configurationService.getFileSystem().getDirectory(dataFile.getFilePath(), true); TableDefinition tableDefinition = this.getTableDefinition(retailerSite, dataFile); String encoding = getDataImportEncoding(tableDefinition, filePath); LineNumberReader lnr = new LineNumberReader(new InputStreamReader(new FileInputStream(filePath), encoding)); lnr.readLine(); // Skip header int numRows = 0; while (lnr.readLine() != null) { numRows++; } lnr.close(); return numRows; } catch (Exception e) { logger.error(String.format("Failed to reading %s data file", filePath), e); dataFile.setStatus(FileStatus.ERROR_READ); dataFileRepository.update(dataFile); return -1; } }
public static void main(String[] args) { if (args.length != 2) { throw new IllegalArgumentException("need char and file"); } LineNumberReader in; try { FileReader fileIn = new FileReader(args[1]); in = new LineNumberReader(fileIn); } catch (FileNotFoundException e) { System.out.println("指定されたファイルが見つかりません。"); return; } String str; try { while ((str = in.readLine()) != null) { if (str.contains(args[0])) { System.out.printf("%3d: %s%n", in.getLineNumber(), str); } } } catch (IOException e) { e.printStackTrace(); } finally { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } }
/** @tests java.io.LineNumberReader#skip(long) */ @TestTargetNew( level = TestLevel.COMPLETE, method = "skip", args = {long.class}) public void test_skipJ() throws IOException { lnr = new LineNumberReader(new StringReader(text)); char[] c = new char[100]; long skipped = lnr.skip(80); assertEquals("Test 1: Incorrect number of characters skipped;", 80, skipped); lnr.read(c, 0, 100); assertTrue( "Test 2: Failed to skip to correct position.", text.substring(80, 180).equals(new String(c, 0, c.length))); try { lnr.skip(-1); fail("Test 3: IllegalArgumentException expected."); } catch (IllegalArgumentException e) { // Expected. } lnr.close(); try { lnr.skip(1); fail("Test 4: IOException expected."); } catch (IOException e) { // Expected. } }
public List<IVecInt> parseInstance() throws IOException, ParseFormatException { skipComments(); readProblemLine(); readConstrs(); in.close(); return clauses; }
/** * Importer with full settings. * * @param filename the file containing the data * @param sep the token which separates the values * @param labelPosition the position of the class label * @return the full list of TrainingSample * @throws IOException */ public static List<TrainingSample<double[]>> importFromFile( String filename, String sep, int labelPosition) throws IOException { // the samples list List<TrainingSample<double[]>> list = new ArrayList<TrainingSample<double[]>>(); LineNumberReader line = new LineNumberReader(new FileReader(filename)); String l; // parse all lines while ((l = line.readLine()) != null) { String[] tok = l.split(","); double[] d = new double[tok.length - 1]; int y = 0; if (labelPosition == -1) { // first n-1 fields are attributes for (int i = 0; i < d.length; i++) d[i] = Double.parseDouble(tok[i]); // last field is class y = Integer.parseInt(tok[tok.length - 1]); } else if (labelPosition < d.length) { for (int i = 0; i < labelPosition; i++) d[i] = Double.parseDouble(tok[i]); for (int i = labelPosition + 1; i < d.length; i++) d[i - 1] = Double.parseDouble(tok[i]); y = Integer.parseInt(tok[labelPosition]); } TrainingSample<double[]> t = new TrainingSample<double[]>(d, y); list.add(t); } line.close(); return list; }
public static CumulativeDistribution readDistributionFromFile(String filename) { Vector x = new Vector(); Vector y = new Vector(); LineNumberReader lnr = null; try { lnr = new LineNumberReader(IOUtils.getBufferedReader(filename)); String line = null; while ((line = lnr.readLine()) != null) { StringTokenizer st = new StringTokenizer(line); x.add(Double.valueOf(st.nextToken())); y.add(Double.valueOf(st.nextToken())); } } catch (FileNotFoundException e) { e.printStackTrace(); if (lnr != null) try { lnr.close(); } catch (IOException e1) { log.warn("Could not close stream.", e); } } catch (IOException e) { e.printStackTrace(); if (lnr != null) try { lnr.close(); } catch (IOException e1) { log.warn("Could not close stream.", e); } } finally { if (lnr != null) try { lnr.close(); } catch (IOException e) { log.warn("Could not close stream.", e); } } double[] xs = new double[x.size()]; double[] ys = new double[x.size()]; for (int i = 0; i < x.size(); i++) { xs[i] = ((Double) x.get(i)).doubleValue(); ys[i] = ((Double) y.get(i)).doubleValue(); } return new CumulativeDistribution(xs, ys); }
public static int getNumberOfLines(String fileName) throws IOException { LineNumberReader lnr; lnr = new LineNumberReader(new FileReader(fileName)); lnr.skip(Long.MAX_VALUE); int numberOfLines = lnr.getLineNumber() + 1; lnr.close(); return numberOfLines; }
public static int countLines(String filename) throws IOException { LineNumberReader reader = new LineNumberReader(new FileReader(filename)); int cnt = 0; String lineRead = ""; while ((lineRead = reader.readLine()) != null) {} cnt = reader.getLineNumber(); reader.close(); return cnt; }
/** * Read a script from the provided resource, using the supplied comment prefix and statement * separator, and build a {@code String} containing the lines. * * <p>Lines <em>beginning</em> with the comment prefix are excluded from the results; however, * line comments anywhere else — for example, within a statement — will be included in * the results. * * @param resource the {@code EncodedResource} containing the script to be processed * @param commentPrefix the prefix that identifies comments in the SQL script — typically * "--" * @param separator the statement separator in the SQL script — typically ";" * @return a {@code String} containing the script lines */ private static String readScript(EncodedResource resource, String commentPrefix, String separator) throws IOException { LineNumberReader lnr = new LineNumberReader(resource.getReader()); try { return readScript(lnr, commentPrefix, separator); } finally { lnr.close(); } }
private static void cierraFichero(LineNumberReader f) { try { if (f != null) { f.close(); } } catch (Exception ex) { log.error("Error al cerrar fichero", ex); } }
public void close() { open = false; if (reader != null) { try { reader.close(); } catch (Exception e) { } } }
public static int countLines(LineNumberReader reader) throws IOException { try { while ((reader.readLine()) != null) ; return reader.getLineNumber(); } catch (Exception ex) { return -1; } finally { if (reader != null) reader.close(); } }
/** * @param file the file to read the line numbers from * @return Number of lines in file * @throws IOException low level file error */ public static int numberOfLines(File file) throws IOException { RandomAccessFile randFile = new RandomAccessFile(file, "r"); long lastRec = randFile.length(); randFile.close(); FileReader fileRead = new FileReader(file); LineNumberReader lineRead = new LineNumberReader(fileRead); lineRead.skip(lastRec); int count = lineRead.getLineNumber() - 1; fileRead.close(); lineRead.close(); return count; }
/** * 加载汉字 * * @throws IOException */ public static void load() throws IOException { InputStream input = ResourceUtil.getResource("character.txt"); LineNumberReader lr = new LineNumberReader(new InputStreamReader(input)); character = new ArrayList<String>(); String line = null; while ((line = lr.readLine()) != null) { for (int i = 0; i < line.length(); i++) { character.add(line.substring(i, i + 1)); } } lr.close(); }
/** * Return true if succeeded, false otherwise * * @param FD * @return */ private boolean undo(File FD) { if (FD.isDirectory()) return false; File parent = FD.getParentFile(); File CVSDIR = new File(parent, "CVS"); if (!CVSDIR.exists()) return false; File entries = new File(CVSDIR, "Entries"); if (!entries.exists()) return false; File entriestemp = new File(CVSDIR, "Entries.temp"); String filename = FD.getName(); boolean success = false; try { LineNumberReader reader = new LineNumberReader(new FileReader(entries)); PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(entriestemp, false))); for (; ; ) { String line = reader.readLine(); if (line == null) break; if (line.equals("")) continue; String parts[] = line.split("/"); boolean skip = false; if (parts.length >= 2 && parts[1].equals(filename)) { // make sure it is scheduled for add/remove if (parts.length >= 3 && parts[2].equals("0")) { // scheduled for add, remove entry skip = true; success = true; } if (parts.length >= 3 && parts[2].startsWith("-")) { // schedule to remove, remove entry line = line.replaceAll("/" + parts[2] + "/", "/" + parts[2].substring(1) + "/"); success = true; } } if (!skip) pw.println(line); } reader.close(); pw.close(); // replace original with modified if (!entriestemp.renameTo(entries)) { System.out.println( "Unable to move " + entriestemp + " to " + entries + ", cannot undo add/remove of " + filename); return false; } } catch (IOException e) { } return success; }
private static long countLines(InputStream inputStream) throws IOException { LineNumberReader lineNumberReader = null; int lines = 1; try { lineNumberReader = new LineNumberReader(new InputStreamReader(inputStream)); lineNumberReader.skip(Long.MAX_VALUE); lines = Math.max(lineNumberReader.getLineNumber(), 1); } finally { if (lineNumberReader != null) { lineNumberReader.close(); } } return lines; }
private void loadExportedParameters() { synchronized (exported_parameters) { try { File parent_dir = new File(SystemProperties.getUserPath()); File props = new File(parent_dir, "exported_params.properties"); if (props.exists()) { LineNumberReader lnr = new LineNumberReader(new InputStreamReader(new FileInputStream(props), "UTF-8")); try { while (true) { String line = lnr.readLine(); if (line == null) { break; } String[] bits = line.split("="); if (bits.length == 2) { String key = bits[0].trim(); String value = bits[1].trim(); if (key.length() > 0 && value.length() > 0) { imported_parameters.put(key, value); } } } } finally { lnr.close(); } } } catch (Throwable e) { e.printStackTrace(); } } COConfigurationManager.setIntDefault("instance.port", Constants.INSTANCE_PORT); registerExportedParameter("instance.port", "instance.port"); }
/** * Read the specified URL and parse the data. * * @param input The URL to read. * @exception IOException If an error occurs while reading the URL or parsing the data. */ public void read(URL input) throws IOException { if (input == null) { throw new IOException("Attempt to read from null input."); } LineNumberReader reader = null; try { reader = new LineNumberReader(new InputStreamReader(input.openStream())); while (true) { // NOTE: The following tolerates all major line terminators. String line = reader.readLine(); if (line == null) { break; } try { // Parse the line. if (_variable == null) { _variable = new Variable(workspace()); _variable.setName("Expression evaluator"); } _variable.setExpression(line); Token token = _variable.getToken(); if (token != null) { _tokens.add(token); // Notify the contained tableaux. Iterator tableaux = entityList(TokenTableau.class).iterator(); while (tableaux.hasNext()) { ((TokenTableau) tableaux.next()).append(token); } } } catch (KernelException ex) { throw new IOException("Error evaluating data expression: " + ex.getMessage()); } } } finally { if (reader != null) { reader.close(); } } }
/** * 获取某个文本文件一共的行数 * * @param filePath 文件的全路径 * @return */ public static int getFileLineNumber(String filePath) { File test = new File(filePath); long fileLength = test.length(); int lines = 0; LineNumberReader rf = null; try { rf = new LineNumberReader(new FileReader(test)); if (rf != null) { rf.skip(fileLength); lines = rf.getLineNumber(); rf.close(); } } catch (IOException e) { if (rf != null) { try { rf.close(); } catch (IOException ee) { } } } finally { return lines + 1; } }
public static String loadDevices(Hashtable devices) { File cf = getConfigFile(); if (cf == null || !cf.exists()) { return null; } Reader fr = null; LineNumberReader lnr = null; try { lnr = new LineNumberReader(fr = new FileReader(cf)); devices.clear(); String line = lnr.readLine(); String selected = null; while (line != null) { if (line.startsWith(devicePrefix)) { DeviceInfo di = new DeviceInfo(); di.loadFromLine(line.substring(devicePrefix.length())); if (di.isValid()) { devices.put(di.btAddress.toLowerCase(), di); } } else if (line.startsWith(selectedPrefix)) { selected = line.substring(selectedPrefix.length()); } else { int p = line.indexOf('='); if (p != -1) { properties.put(line.substring(0, p), line.substring(p + 1)); } } line = lnr.readLine(); } return selected; } catch (Throwable e) { Logger.debug(e); return null; } finally { if (lnr != null) { try { lnr.close(); } catch (IOException e) { } } if (fr != null) { try { fr.close(); } catch (IOException e) { } } } }