List of usage examples for java.io BufferedReader mark
public void mark(int readAheadLimit) throws IOException
From source file:Main.java
public static void main(String[] args) throws Exception { InputStream is = new FileInputStream("c:/test.txt"); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); System.out.println((char) br.read()); System.out.println((char) br.read()); br.mark(26); System.out.println("mark() invoked"); System.out.println((char) br.read()); System.out.println((char) br.read()); br.reset();/*from w w w . j av a 2 s. com*/ System.out.println("reset() invoked"); System.out.println((char) br.read()); System.out.println((char) br.read()); }
From source file:Main.java
public static void main(String[] args) throws Exception { String s = "from java2s.com"; StringReader sr = new StringReader(s); BufferedReader br = new BufferedReader(sr); // reads and prints BufferedReader System.out.println((char) br.read()); System.out.println((char) br.read()); // mark invoked at this position br.mark(0); System.out.println("mark() invoked"); System.out.println((char) br.read()); System.out.println((char) br.read()); // reset() repositioned the stream to the mark br.reset();// w ww . j a va2 s. co m System.out.println("reset() invoked"); System.out.println((char) br.read()); System.out.println((char) br.read()); }
From source file:org.bitbucket.mlopatkin.android.liblogcat.file.FileDataSourceFactory.java
public static DataSource createDataSource(File file) throws UnrecognizedFormatException, IOException { // check first non-empty line of the file BufferedReader in = new BufferedReader(new FileReader(file)); try {/*ww w . j a v a 2 s.c om*/ in.mark(READ_AHEAD_LIMIT); String checkLine = getFirstNonEmptyLine(in); while (checkLine != null && LogRecordParser.isLogBeginningLine(checkLine)) { in.mark(READ_AHEAD_LIMIT); checkLine = getFirstNonEmptyLine(in); } if (DUMPSTATE_FIRST_LINE.equals(checkLine)) { return createDumpstateFileSource(file, in); } else { return createLogFileSource(file, checkLine, in); } } finally { in.close(); } }
From source file:Main.java
public static String findObject(BufferedReader br, String type) throws IOException { String prefix = "-----BEGIN "; String suffix = (type == null) ? "-----" : type + "-----"; while (true) { br.mark(1024); String line = br.readLine(); if (null == line) { return null; }/*from w ww .j a va 2 s. c o m*/ if (!line.startsWith(prefix)) { continue; } if (!line.endsWith(suffix)) { continue; } br.reset(); return line.substring(prefix.length(), line.length() - 5); } }
From source file:com.liusoft.dlog4j.xml.RSSFetcher.java
/** * ??//from ww w. j av a2 s . c o m * @param type * @param url * @return * @throws IOException * @throws HttpException * @throws SAXException * @throws ParseException */ private static Channel fetchChannelViaHTTP(String url) throws HttpException, IOException, SAXException { Digester parser = new XMLDigester(); GetMethod get = new GetMethod(url); //get.setRequestHeader("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; zh-cn) Opera 8.52"); try { http_client.executeMethod(get); if (get.getStatusCode() == HttpServletResponse.SC_OK) { Charset cs = null; Header header_cs = getResponseHeader(get, "Content-Type"); if (header_cs == null) { cs = Charset.forName(get.getResponseCharSet()); } else { String content_type = header_cs.getValue().toLowerCase(); try { Object[] values = content_type_parser.parse(content_type); cs = Charset.forName((String) values[1]); } catch (ParseException e) { URL o_url = new URL(url); String host = o_url.getHost(); Iterator hosts = charsets.keySet().iterator(); while (hosts.hasNext()) { String t_host = (String) hosts.next(); if (host.toLowerCase().endsWith(t_host)) { cs = Charset.forName((String) charsets.get(t_host)); break; } } if (cs == null) cs = default_charset; } } BufferedReader rd = new BufferedReader(new InputStreamReader(get.getResponseBodyAsStream(), cs)); char[] cbuf = new char[1]; int read_idx = 1; do { rd.mark(read_idx++); if (rd.read(cbuf) == -1) break; if (cbuf[0] != '<') continue; rd.reset(); break; } while (true); return (Channel) parser.parse(rd); } else { log.error("Fetch RSS from " + url + " failed, code=" + get.getStatusCode()); } } finally { get.releaseConnection(); } return null; }
From source file:net.sourceforge.users.dragomerlin.vcs2icsCalendarConverter.ConvertSingleFile.java
private static String readPossibleMultiline(String fieldContent, BufferedReader inStream) throws IOException { char[] buf = new char[1]; boolean multilineFound = false; do {// www.ja v a 2s. c o m inStream.mark(1); int res = inStream.read(buf); if (res == -1) { throw new IOException("Error while reading multiline: EOF."); } if (buf[0] == ' ') { multilineFound = true; String line = inStream.readLine(); fieldContent += line; } else { multilineFound = false; } } while (multilineFound); inStream.reset(); return fieldContent; }
From source file:org.apache.any23.mime.TikaMIMETypeDetector.java
/** * Extracts a sample data from the input stream, from the current * mark to the first <i>breakChar</i> char. * * @param is the input stream to sample. * @param breakChar the char to break to sample. * @return the sample string.//from ww w . j a v a 2s . c o m * @throws IOException if an error occurs during sampling. */ private static StringBuilder extractDataSample(InputStream is, char breakChar, char[] insideBlockCharacters, char[] lineCommentChars, char[] outsideBlockCharacters, char[] switchBlockCharacters) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); // TODO: Make this configurable final int MAX_SIZE = 1024 * 2; int c; boolean insideBlock = false; int read = 0; br.mark(MAX_SIZE); try { while ((c = br.read()) != -1) { read++; if (sb.length() > MAX_SIZE) { break; } if (!insideBlock) { for (char nextLineCommentChar : lineCommentChars) { // if we hit a comment character that signals the rest of the line is a comment // then we do not want to extract any of the rest of the line, including the // comment character for our sample, so we read to the end of the line and then // continue the loop without appending anything if (c == nextLineCommentChar) { br.readLine(); continue; } } } for (char nextInsideChar : insideBlockCharacters) { if (c == nextInsideChar) insideBlock = true; } for (char nextOutsideChar : outsideBlockCharacters) { if (c == nextOutsideChar) insideBlock = false; } for (char nextSwitchChar : switchBlockCharacters) { if (c == nextSwitchChar) insideBlock = !insideBlock; } sb.append((char) c); if (!insideBlock && breakChar == c) { break; } } } finally { is.reset(); br.reset(); } return sb; }
From source file:com.dropbox.client2.RESTUtility.java
/** * Reads in content from an {@link HttpResponse} and parses it as JSON. * * @param response the {@link HttpResponse}. * * @return a parsed JSON object, typically a Map or a JSONArray. * * @throws DropboxServerException if the server responds with an error * code. See the constants in {@link DropboxServerException} for * the meaning of each error code. * @throws DropboxIOException if any network-related error occurs while * reading in content from the {@link HttpResponse}. * @throws DropboxUnlinkedException if the user has revoked access. * @throws DropboxParseException if a malformed or unknown response was * received from the server.//from w w w .j a v a 2 s .c om * @throws DropboxException for any other unknown errors. This is also a * superclass of all other Dropbox exceptions, so you may want to * only catch this exception which signals that some kind of error * occurred. */ public static Object parseAsJSON(HttpResponse response) throws DropboxException { Object result = null; BufferedReader bin = null; try { HttpEntity ent = response.getEntity(); if (ent != null) { InputStreamReader in = new InputStreamReader(ent.getContent()); // Wrap this with a Buffer, so we can re-parse it if it's // not JSON // Has to be at least 16384, because this is defined as the buffer size in // org.json.simple.parser.Yylex.java // and otherwise the reset() call won't work bin = new BufferedReader(in, 16384); bin.mark(16384); JSONParser parser = new JSONParser(); result = parser.parse(bin); } } catch (IOException e) { throw new DropboxIOException(e); } catch (ParseException e) { if (DropboxServerException.isValidWithNullBody(response)) { // We have something from Dropbox, but it's an error with no reason throw new DropboxServerException(response); } else { // This is from Dropbox, and we shouldn't be getting it throw new DropboxParseException(bin); } } catch (OutOfMemoryError e) { throw new DropboxException(e); } finally { if (bin != null) { try { bin.close(); } catch (IOException e) { } } } int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != DropboxServerException._200_OK) { if (statusCode == DropboxServerException._401_UNAUTHORIZED) { throw new DropboxUnlinkedException(); } else { throw new DropboxServerException(response, result); } } return result; }
From source file:net.sourceforge.vulcan.web.ParameterParsingHttpServletRequestWrapper.java
@SuppressWarnings({ "rawtypes", "unchecked" }) @Override/*from w ww .j a v a 2s.co m*/ public Map getParameterMap() { if (parameterMap != null) { return parameterMap; } parameterMap = new HashMap<String, String>(super.getParameterMap()); parameterMultiMap = new MultiHashMap(); for (Enumeration e = super.getParameterNames(); e.hasMoreElements();) { String name = (String) e.nextElement(); for (String v : super.getParameterValues(name)) { parameterMultiMap.put(name, v); } } if (!StringUtils.equals(getContentType(), "application/x-www-form-urlencoded")) { return parameterMultiMap; } String encoding = getCharacterEncoding(); if (StringUtils.isBlank(encoding)) { encoding = "UTF-8"; } try { BufferedReader reader = getReader(); reader.mark(8192); String formData = IOUtils.toString(reader); reader.reset(); for (String kvp : formData.split("&")) { String[] kv = kvp.split("="); String key = URLDecoder.decode(kv[0], encoding); String value = kv.length > 1 ? URLDecoder.decode(kv[1], encoding) : StringUtils.EMPTY; parameterMultiMap.put(key, value); if (!parameterMap.containsKey(key)) { parameterMap.put(key, value); } } } catch (IOException ex) { throw new RuntimeException(ex); } return parameterMap; }
From source file:org.uva.itast.blended.omr.PageTemplate.java
/** * Mtodo que lee las marcas de un objeto BufferedReader y las almacena en un objeto tipo Campo * @param in/* www. j a v a2 s . c om*/ * @throws IOException */ public void leerMarcas(BufferedReader in) throws IOException { String line; in.mark(20); //marcamos para recordar la posicin anterior donde termino la lectura de in while ((line = in.readLine()) != null && !line.equals("")) { if (line.startsWith("[Page")) //etiqueta de principio de pgina { if (logger.isDebugEnabled()) { logger.debug("leerMarcas(BufferedReader) - Pgina siguiente"); //$NON-NLS-1$ } in.reset(); return; } else //lectura de fields de una lnea { Field campo; try { campo = new Field(line); fields.put(campo.getName(), campo); marcas.add(campo.getName()); //almacenamos en el array marcas[] la clave } catch (IllegalArgumentException e) // bad field especification { logger.warn("Field ignored.", e); } } in.mark(20); // mark position for next page } }