Java Code Examples for java.io.BufferedReader#mark()
The following examples show how to use
java.io.BufferedReader#mark() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TaskIo.java From jdotxt with GNU General Public License v3.0 | 7 votes |
private static String readLine(BufferedReader r) throws IOException { StringBuilder sb = new StringBuilder(); boolean eol = false; int c; while(!eol && (c = r.read()) >= 0) { sb.append((char)c); eol = (c == '\r' || c == '\n'); // check for \r\n if (c == '\r') { r.mark(1); c = r.read(); if (c != '\n') { r.reset(); } else { sWindowsLineBreaks = true; sb.append((char)c); } } } return sb.length() == 0 ? null : sb.toString(); }
Example 2
Source File: LoadConfigurationServlet.java From candybean with GNU Affero General Public License v3.0 | 6 votes |
private FormData getFormData() throws CandybeanException, IOException{ Candybean candybean = Candybean.getInstance(); File configFile = candybean.config.configFile; BufferedReader br = new BufferedReader(new FileReader(configFile)); FormData formData = new FormData(); formData.setHeader(readHeader(br)); @SuppressWarnings("unused") String line; br.mark(0); while ((line = br.readLine()) != null) { try { br.reset(); formData.getFormFields().add(new FormFieldData(readComments(br), readKeyValueEntry(br))); br.mark(0); } catch (Exception e) { continue; } } br.close(); return formData; }
Example 3
Source File: CsvUtil.java From openscoring with GNU Affero General Public License v3.0 | 6 votes |
static public CsvPreference getFormat(BufferedReader reader) throws IOException { reader.mark(10 * 1024); for(int i = 0; i < CsvUtil.DELIMITERS.length; i++){ char delimiter = CsvUtil.DELIMITERS[i]; try { CsvPreference format = createFormat(delimiter, '\"'); if(checkFormat(reader, format)){ return format; } } finally { reader.reset(); } } throw new IOException("Unrecognized CSV format"); }
Example 4
Source File: JHLogAnalyzer.java From hadoop with Apache License 2.0 | 6 votes |
private String readLine(BufferedReader reader) throws IOException { resBuffer.setLength(0); reader.mark(maxJobDelimiterLineLength); for(String line = reader.readLine(); line != null; line = reader.readLine()) { if(isEndOfJobLog(line)) { if(resBuffer.length() == 0) resBuffer.append(line); else reader.reset(); break; } if(resBuffer.length() == 0) resBuffer.append(line); else if(resBuffer.length() < 32000) resBuffer.append(line); if(line.endsWith(" .") || line.endsWith("\" ")) { break; } reader.mark(maxJobDelimiterLineLength); } String result = resBuffer.length() == 0 ? null : resBuffer.toString(); resBuffer.setLength(0); return result; }
Example 5
Source File: LoadConfigurationServlet.java From candybean with GNU Affero General Public License v3.0 | 6 votes |
private String readKeyValueEntry(BufferedReader br) throws IOException { String line; String keyValueEntry = ""; int keyValuePairsEncountered = 0; br.mark(0); while ((line = br.readLine()) != null) { if(line.contains("=")){ keyValuePairsEncountered++; } if(!line.startsWith("#") && !line.isEmpty() && keyValuePairsEncountered <= 1){ keyValueEntry = keyValueEntry.concat(line); }else{ br.reset(); break; } br.mark(0); } return keyValueEntry; }
Example 6
Source File: DbExtractorTest.java From reladomo with Apache License 2.0 | 6 votes |
static void skipHeader(BufferedReader in) throws IOException { boolean done = false; boolean inComment = false; while(!done) { in.mark(10000); String line = in.readLine().trim(); if (inComment) { if (line.endsWith("*/")) { inComment = false; } } else if (line.startsWith("/*")) { inComment = true; } else if (!line.isEmpty()) { in.reset(); done = true; } } }
Example 7
Source File: SunJDKParser.java From tda with GNU Lesser General Public License v2.1 | 6 votes |
/** * parses a loggc file stream and reads any found class histograms and adds the to the dump store * @param loggcFileStream the stream to read * @param root the root node of the dumps. */ public void parseLoggcFile(InputStream loggcFileStream, DefaultMutableTreeNode root) { BufferedReader bis = new BufferedReader(new InputStreamReader(loggcFileStream)); Vector histograms = new Vector(); try { while (bis.ready()) { bis.mark(getMarkSize()); String nextLine = bis.readLine(); if (nextLine.startsWith("num #instances #bytes class name")) { bis.reset(); histograms.add(parseNextClassHistogram(bis)); } } // now add the found histograms to the tree. for (int i = histograms.size() - 1; i >= 0; i--) { DefaultMutableTreeNode dump = getNextDumpForHistogram(root); if (dump != null) { addHistogramToDump(dump, (HistogramTableModel) histograms.get(i)); } } } catch (IOException ex) { ex.printStackTrace(); } }
Example 8
Source File: AzureCISBenchmarkImporter.java From clouditor with Apache License 2.0 | 6 votes |
private String readUntilBefore(BufferedReader reader, String needle) throws IOException { var buffer = new StringBuilder(); while (true) { // mark the beginning of the line, so we can return to it reader.mark(2048); // read the line var line = reader.readLine(); if (line == null) { return null; } // see if it matches a section if (line.trim().matches(needle)) { // reset to mark reader.reset(); // return buffer return buffer.toString().trim(); } buffer.append(line); } }
Example 9
Source File: LoadConfigurationServlet.java From candybean with GNU Affero General Public License v3.0 | 6 votes |
private String readComments(BufferedReader br) throws IOException { String line; String comments = ""; br.mark(0); while ((line = br.readLine()) != null) { if(line.startsWith("#") || line.isEmpty()){ comments = comments.concat(line); }else{ br.reset(); break; } br.mark(0); } return comments; }
Example 10
Source File: OldBufferedReaderTest.java From j2objc with Apache License 2.0 | 6 votes |
public void testSourceThrowsWithMark() throws IOException { br = new BufferedReader(new ThrowingReader( new StringReader("ABCDEFGHI"), 4)); br.read(); br.read(); br.mark(10); br.read(); br.read(); try { br.read(); fail(); } catch (IOException fromThrowingReader) { } assertEquals('E', br.read()); assertEquals('F', br.read()); }
Example 11
Source File: OpenTsdbHttpFormatParser.java From chronix.server with Apache License 2.0 | 5 votes |
/** * Determines if the given reader contains a single or multiple metrics. * * @param reader Reader. * @return True if the reader contains a single metric, false if the reader contains multiple. * @throws FormatParseException If something went wrong. */ private boolean containsSingleMetric(BufferedReader reader) throws FormatParseException { try { // Need to reset the reader after reading the first char reader.mark(1); char firstChar = (char) reader.read(); reader.reset(); // If '{', single metric. Multiple metrics start with '[' return firstChar == '{'; } catch (IOException e) { throw new FormatParseException("IOException while determining if single or multiple metrics ", e); } }
Example 12
Source File: BinnedDataDouble.java From housing-model with MIT License | 5 votes |
/** * Loads data from a .csv file. The file should be in the format {bin min, min max, value}, with as many initial * rows as needed for comments but always marked with an initial "#" character * * @param filename Address of the file to read data from */ public BinnedDataDouble(String filename) { super(0.0,0.0); try { // Open file and buffered readers FileReader in = new FileReader(filename); BufferedReader buffReader = new BufferedReader(in); // Skip initial comment lines keeping mark of previous position to return to if line is not comment buffReader.mark(1000); // 1000 is just the number of characters that can be read while preserving the mark String line = buffReader.readLine(); while (line.charAt(0) == '#') { buffReader.mark(1000); line = buffReader.readLine(); } buffReader.reset(); // Return to previous position (before reading the first line that was not a comment) // Pass advanced buffered reader to CSVFormat parser Iterator<CSVRecord> records = CSVFormat.EXCEL.parse(buffReader).iterator(); CSVRecord record; // Read through records if(records.hasNext()) { record = records.next(); // Use the first record to set the first bin minimum and the bin width... this.setFirstBinMin(Double.valueOf(record.get(0))); this.setBinWidth(Double.valueOf(record.get(1))-firstBinMin); // ...before actually adding it to the array add(Double.valueOf(record.get(2))); while(records.hasNext()) { record = records.next(); // Next records are just added to the array add(Double.valueOf(record.get(2))); } } } catch (IOException e) { System.out.println("Problem while loading data from " + filename + " for creating a BinnedDataDouble object"); e.printStackTrace(); } }
Example 13
Source File: Event.java From log-synth with Apache License 2.0 | 5 votes |
public static Event read(BufferedReader in) throws IOException { in.mark(1000); String line = in.readLine(); if (line == null) { return null; } try { Matcher m = format.matcher(line); if (m.matches()) { int i = 1; Date d = df.parse(m.group(i++)); String op = m.group(i++); int uid = Integer.parseInt(m.group(i++), 16); int ip = Integer.parseInt(m.group(i++)) << 24; ip += Integer.parseInt(m.group(i++)) << 16; ip += Integer.parseInt(m.group(i++)) << 8; ip += Integer.parseInt(m.group(i)); return new Event(uid, d.getTime(), ip, op); } else { in.reset(); return null; } } catch (ParseException | NumberFormatException e) { in.reset(); return null; } }
Example 14
Source File: CsvHelper.java From openScale with GNU General Public License v3.0 | 5 votes |
public static List<ScaleMeasurement> importFrom(BufferedReader reader) throws IOException, ParseException { CsvProcessor<ScaleMeasurement> csvProcessor = new CsvProcessor<>(ScaleMeasurement.class) .withHeaderValidation(true) .withFlexibleOrder(true) .withAlwaysTrimInput(true) .withAllowPartialLines(true); csvProcessor.setColumnNameMatcher(new ColumnNameMatcher() { @Override public boolean matchesColumnName(String definitionName, String csvName) { return definitionName.equals(csvName) || (definitionName.equals("lbm") && csvName.equals("lbw")); } }); reader.mark(1000); try { csvProcessor.readHeader(reader, null); } catch (ParseException ex) { // Try to import it as an old style CSV export reader.reset(); final String sampleLine = reader.readLine(); reader.reset(); final String[] header = getOldStyleHeaders(sampleLine); if (header == null) { // Don't know what to do with this, let Simple CSV error out return csvProcessor.readAll(reader, null); } csvProcessor.validateHeaderColumns(header, null); } return csvProcessor.readRows(reader, null); }
Example 15
Source File: LoadConfigurationServlet.java From candybean with GNU Affero General Public License v3.0 | 5 votes |
private String readHeader(BufferedReader br) throws IOException { String line; String header = ""; br.mark(0); while ((line = br.readLine()) != null) { if(line.startsWith("###") || line.isEmpty()){ header = header.concat(line); }else{ br.reset(); break; } br.mark(0); } return header; }
Example 16
Source File: Version2to4TransformingReader.java From morf with Apache License 2.0 | 5 votes |
/** * Tests whether a given input stream contains XML format 2, and therefore * should have the transform applied. * <p> * This is designed to match the known output format of * {@link XmlDataSetConsumer} which previously produced invalid XML. It is * deliberately brittle. There is no need for a more intelligent XML parser * here. * </p> * * @param bufferedReader The input stream in a buffered reader * @return true if the transform should be applied. (because it's format 2) */ static int readVersion(BufferedReader bufferedReader) { try { bufferedReader.mark(1024); // arbitrary read-ahead limit - that's enough to get the info we want try { char[] buffer = new char[1024]; int read = bufferedReader.read(buffer); if (read == -1) { return -1; } String content = new String(buffer, 0, read); // Apply the transform if the version number is 2 or 1 Pattern pattern = Pattern.compile("table\\sversion=\"(\\d+)\""); // Matcher matcher = pattern.matcher(content); if (!matcher.find()) { return -1; } else { return Integer.parseInt(matcher.group(1)); } } finally { bufferedReader.reset(); } } catch (IOException e) { throw new RuntimeException(e); } }
Example 17
Source File: EpubBook.java From BookyMcBookface with GNU General Public License v3.0 | 5 votes |
private static Map<String,?> processToc(BufferedReader tocReader) { Map<String,Object> bookdat = new LinkedHashMap<>(); DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); XPathFactory factory = XPathFactory.newInstance(); DocumentBuilder builder = null; try { builder = dfactory.newDocumentBuilder(); tocReader.mark(4); if ('\ufeff' != tocReader.read()) tocReader.reset(); // not the BOM marker Document doc = builder.parse(new InputSource(tocReader)); XPath tocPath = factory.newXPath(); tocPath.setNamespaceContext(tocnsc); Node nav = (Node)tocPath.evaluate("/ncx/navMap", doc, XPathConstants.NODE); int total = readNavPoint(nav, tocPath, bookdat, 0); bookdat.put(TOCCOUNT, total); } catch (ParserConfigurationException | IOException | SAXException | XPathExpressionException e) { Log.e("BMBF", "Error parsing xml " + e.getMessage(), e); } return bookdat; }
Example 18
Source File: EpubBook.java From BookyMcBookface with GNU General Public License v3.0 | 5 votes |
private static List<String> getRootFilesFromContainer(BufferedReader containerxml) { List<String> rootFiles = new ArrayList<>(); try { containerxml.mark(4); if ('\ufeff' != containerxml.read()) containerxml.reset(); // not the BOM marker XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(false); XmlPullParser xpp = factory.newPullParser(); xpp.setInput(containerxml); int eventType = xpp.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { if (xpp.getName().equals("rootfile")) { for (int i = 0; i < xpp.getAttributeCount(); i++) { if (xpp.getAttributeName(i).equals("full-path")) { rootFiles.add(xpp.getAttributeValue(i)); } } } } eventType = xpp.next(); } } catch (Exception e) { Log.e("BMBF", "Error parsing xml " + e, e); } return rootFiles; }
Example 19
Source File: MatrixMarketReader.java From Drop-seq with MIT License | 5 votes |
private static String readAndReset(final BufferedReader reader, final int numChars) { try { reader.mark(numChars); final char[] buf = new char[numChars]; final int charsRead = reader.read(buf); reader.reset(); if (charsRead != numChars) { return null; } return new String(buf); } catch (IOException e) { throw new RuntimeIOException(e); } }
Example 20
Source File: MimeHelper.java From azure-storage-android with Apache License 2.0 | 4 votes |
/** * Reserved for internal use. A static factory method that generates a {@link MimePart} containing the next MIME * part read from the {@link BufferedReader}. * The {@link BufferedReader} is left positioned at the start of the next MIME boundary header. * * @param reader * The {@link BufferedReader} containing the response stream to parse. * @param boundary * A <code>String</code> containing the MIME part boundary string. * An {@link OperationContext} object for tracking the current operation. Specify <code>null</code> to * safely ignore operation context. * @return * A {@link MimePart} constructed by parsing the next MIME part data from the {@link BufferedReader}. * @throws IOException * if an error occured accessing the input stream. * @throws StorageException * if an error occured parsing the input stream. */ private static MimePart readMimePart(final BufferedReader reader, final String boundary, final OperationContext opContext) throws IOException, StorageException { final MimePart retPart = new MimePart(); // Read HttpStatus code String tempStr = getNextLineSkippingBlankLines(reader); if (!tempStr.startsWith("HTTP/1.1 ")) { throw generateMimeParseException(); } final String[] headerVals = tempStr.split(" "); if (headerVals.length < 3) { throw generateMimeParseException(); } retPart.httpStatusCode = Integer.parseInt(headerVals[1]); // "HTTP/1.1 XXX ".length() => 13 retPart.httpStatusMessage = tempStr.substring(13); // Read headers tempStr = reader.readLine(); while (tempStr != null && tempStr.length() > 0) { final String[] headerParts = tempStr.split(": "); if (headerParts.length < 2) { throw generateMimeParseException(); } retPart.headers.put(headerParts[0], headerParts[1]); tempStr = reader.readLine(); } // Store json payload reader.mark(1024 * 1024); tempStr = getNextLineSkippingBlankLines(reader); if (tempStr == null) { throw generateMimeParseException(); } // empty body if (tempStr.startsWith(boundary)) { reader.reset(); retPart.payload = Constants.EMPTY_STRING; return retPart; } final StringBuilder payloadBuilder = new StringBuilder(); // read until mime closure or end of file while (!tempStr.startsWith(boundary)) { payloadBuilder.append(tempStr); reader.mark(1024 * 1024); tempStr = getNextLineSkippingBlankLines(reader); if (tempStr == null) { throw generateMimeParseException(); } } // positions stream at start of next MIME Header reader.reset(); retPart.payload = payloadBuilder.toString(); return retPart; }