Java Code Examples for java.io.BufferedReader.read()

The following are Jave code examples for showing how to use read() of the java.io.BufferedReader class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: whackpad   File: BetterFile.java   Source Code and License Vote up 9 votes
public static String getReaderString(BufferedReader reader) {
  StringBuffer out = new StringBuffer();
  char[] c = new char[8192];
  try {
    for (int n; (n = reader.read(c, 0, c.length)) != -1;) {
      out.append(c, 0, n);
    }
    reader.close();
  } catch (IOException e) {
    e.printStackTrace();
    return null;
  }
  return out.toString();
}
 
Example 2
Project: guava-mock   File: CharSourceTest.java   Source Code and License Vote up 6 votes
public void testOpenBufferedStream() throws IOException {
  BufferedReader reader = source.openBufferedStream();
  assertTrue(source.wasStreamOpened());
  assertFalse(source.wasStreamClosed());

  StringWriter writer = new StringWriter();
  char[] buf = new char[64];
  int read;
  while ((read = reader.read(buf)) != -1) {
    writer.write(buf, 0, read);
  }
  reader.close();
  writer.close();

  assertTrue(source.wasStreamClosed());
  assertEquals(STRING, writer.toString());
}
 
Example 3
Project: ClassroomFlipkart   File: SQLOutputImpl.java   Source Code and License Vote up 6 votes
/**
 * Writes a stream of uninterpreted bytes to this <code>SQLOutputImpl</code>
 * object.
 *
 * @param x the value to pass to the database
 * @throws SQLException if the <code>SQLOutputImpl</code> object is in
 *        use by a <code>SQLData</code> object attempting to write the attribute
 *        values of a UDT to the database.
 */
@SuppressWarnings("unchecked")
public void writeBinaryStream(java.io.InputStream x) throws SQLException {
     BufferedReader bufReader = new BufferedReader(new InputStreamReader(x));
     try {
           int i;
         while( (i=bufReader.read()) != -1 ) {
            char ch = (char)i;

            StringBuffer strBuf = new StringBuffer();
            strBuf.append(ch);

            String str = new String(strBuf);
            String strLine = bufReader.readLine();

            writeString(str.concat(strLine));
         }
    } catch(IOException ioe) {
        throw new SQLException(ioe.getMessage());
    }
}
 
Example 4
Project: pandionj   File: JavaSourceParser.java   Source Code and License Vote up 6 votes
private static String readFileToString(String filePath) {
	StringBuilder fileData = new StringBuilder(1000);
	try {
		BufferedReader reader = new BufferedReader(new FileReader(filePath));

		char[] buf = new char[10];
		int numRead = 0;
		while ((numRead = reader.read(buf)) != -1) {
			String readData = String.valueOf(buf, 0, numRead);
			fileData.append(readData);
			buf = new char[1024];
		}
		reader.close();
	}
	catch(IOException e) {
		e.printStackTrace();
	}
	return fileData.toString();	
}
 
Example 5
Project: OpenJSharp   File: SQLOutputImpl.java   Source Code and License Vote up 6 votes
/**
 * Writes a stream of Unicode characters to this
 * <code>SQLOutputImpl</code> object. The driver will do any necessary
 * conversion from Unicode to the database <code>CHAR</code> format.
 *
 * @param x the value to pass to the database
 * @throws SQLException if the <code>SQLOutputImpl</code> object is in
 *        use by a <code>SQLData</code> object attempting to write the attribute
 *        values of a UDT to the database.
 */
@SuppressWarnings("unchecked")
public void writeCharacterStream(java.io.Reader x) throws SQLException {
     BufferedReader bufReader = new BufferedReader(x);
     try {
         int i;
         while( (i = bufReader.read()) != -1 ) {
            char ch = (char)i;
            StringBuffer strBuf = new StringBuffer();
            strBuf.append(ch);

            String str = new String(strBuf);
            String strLine = bufReader.readLine();

            writeString(str.concat(strLine));
         }
     } catch(IOException ioe) {

     }
}
 
Example 6
Project: ClassroomFlipkart   File: SQLOutputImpl.java   Source Code and License Vote up 6 votes
/**
 * Writes a stream of Unicode characters to this
 * <code>SQLOutputImpl</code> object. The driver will do any necessary
 * conversion from Unicode to the database <code>CHAR</code> format.
 *
 * @param x the value to pass to the database
 * @throws SQLException if the <code>SQLOutputImpl</code> object is in
 *        use by a <code>SQLData</code> object attempting to write the attribute
 *        values of a UDT to the database.
 */
@SuppressWarnings("unchecked")
public void writeCharacterStream(java.io.Reader x) throws SQLException {
     BufferedReader bufReader = new BufferedReader(x);
     try {
         int i;
         while( (i = bufReader.read()) != -1 ) {
            char ch = (char)i;
            StringBuffer strBuf = new StringBuffer();
            strBuf.append(ch);

            String str = new String(strBuf);
            String strLine = bufReader.readLine();

            writeString(str.concat(strLine));
         }
     } catch(IOException ioe) {

     }
}
 
Example 7
Project: JInsight   File: ApptuitPutClient.java   Source Code and License Vote up 6 votes
private String consumeResponse(InputStream inputStr, Charset encoding) {
  StringBuilder body = new StringBuilder();
  BufferedReader reader = new BufferedReader(new InputStreamReader(inputStr, encoding));
  try {
    int i;
    char[] cbuf = new char[BUFFER_SIZE];
    while ((i = reader.read(cbuf)) > 0) {
      if (body == null) {
        continue;
      }
      if (body.length() + i >= MAX_RESP_LENGTH) {
        body = null;
      } else {
        body.append(cbuf, 0, i);
      }
    }
  } catch (IOException e) {
    LOGGER.error("Error reading response", e);
  }
  return body == null ? "Response too long" : body.toString();
}
 
Example 8
Project: incubator-netbeans   File: LineDiffTest.java   Source Code and License Vote up 5 votes
private String getFileContent(File f) throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(f));
    char[] buffer = new char[1024];
    int read = br.read(buffer);
    String t = new String(buffer, 0, read);
    String ls = System.getProperty("line.separator");
    return t.replace(ls, "\n");
}
 
Example 9
Project: Cognizant-Intelligent-Test-Scripter   File: InjectScript.java   Source Code and License Vote up 5 votes
private void printLines(InputStream ins) throws IOException {
    int line;
    BufferedReader in = new BufferedReader(
            new InputStreamReader(ins));
    while ((line = in.read()) != -1) {
        consoleOutputStream.write(line);
    }
}
 
Example 10
Project: bootstrap   File: CsvForJpaTest.java   Source Code and License Vote up 5 votes
@Test
public void toJpaNoValues() throws Exception {
	final BufferedReader bufferedReader = new BufferedReader(new StringReader("\n"), 1);
	bufferedReader.read();
	final List<DummyEntity> jpa = csvForJpa.toJpa(DummyEntity.class, bufferedReader, false);
	Assert.assertTrue(jpa.isEmpty());
}
 
Example 11
Project: open-rmbt   File: JSONParser.java   Source Code and License Vote up 5 votes
public static String sendToUrl(final URL url, final String data, int connectTimeout) throws IOException
{
    final HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    try {
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        
        urlConnection.setConnectTimeout(connectTimeout);
        urlConnection.setReadTimeout(READ_TIMEOUT);
        
        urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        urlConnection.setRequestProperty("Accept", "application/json");
        
        final byte[] bytes = data.getBytes(Charset.forName("UTF-8"));
        urlConnection.setFixedLengthStreamingMode(bytes.length);
        urlConnection.getOutputStream().write(bytes);
        
        final StringBuilder stringBuilder = new StringBuilder();
        final BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        int read;
        final char[] chars = new char[1024];
        while ((read = reader.read(chars)) != -1)
            stringBuilder.append(chars, 0, read);
        return stringBuilder.toString();
    } finally {
        urlConnection.disconnect();
    }
}
 
Example 12
Project: incubator-netbeans   File: SCFTHandlerTest.java   Source Code and License Vote up 5 votes
private static String readChars(FileObject fo, Charset set) throws IOException {
    CharBuffer arr = CharBuffer.allocate((int)fo.getSize() * 2);
    BufferedReader r = new BufferedReader(new InputStreamReader(fo.getInputStream(), set));
    while (r.read(arr) != -1) {
        // again
    }
    r.close();
    
    arr.flip();
    return arr.toString();
}
 
Example 13
Project: DNASDKJava   File: JNumber.java   Source Code and License Vote up 5 votes
static JNumber parseNumber(BufferedReader reader) throws IOException {
    skipSpace(reader);
    StringBuilder sb = new StringBuilder();
    while (true) {
    	reader.mark(1);
        int c = reader.read();
        if (c >= '0' && c <= '9' || c == '.' || c == '-') {
            sb.append((char)c);
        } else {
        	reader.reset();
            break;
        }
    }
    return new JNumber(Double.parseDouble(sb.toString()));
}
 
Example 14
Project: incubator-netbeans   File: Convertors.java   Source Code and License Vote up 5 votes
/**
 * Wrap reader into buffered one and start reading returning
 * String as a EOF is reached.
 */
public static String readerToString(Reader reader) throws IOException {
    
    BufferedReader fastReader = new BufferedReader(reader);
    StringBuffer buf = new StringBuffer(1024);
    try {
        for (int i = fastReader.read(); i >= 0; i = fastReader.read()) {
            buf.append((char)i);                            
        }
    } catch (EOFException eof) {
        //expected
    }

    return buf.toString();        
}
 
Example 15
Project: MultiScreenFramework   File: Info.java   Source Code and License Vote up 5 votes
/**
 * Gets the framework usage as a formatted string.
 *
 * @return - The framework usage as string to be printed to console via
 * System.out.print()
 */
public static String getFrameworkUsage() {
    try {
        InputStream is = Info.class.getClass().getResourceAsStream("/screenframework/com/zilabs/frameworkinfo/usage");
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        sb.setLength(0);
        while (br.read() > 1) {
            sb.append(br.readLine());
            sb.append("\n");
        }
    } catch (IOException e) {
        return e.getMessage();
    }
    return sb.toString();
}
 
Example 16
Project: guava-mock   File: CharSourceTester.java   Source Code and License Vote up 5 votes
public void testOpenBufferedStream() throws IOException {
  BufferedReader reader = source.openBufferedStream();

  StringWriter writer = new StringWriter();
  char[] buf = new char[64];
  int read;
  while ((read = reader.read(buf)) != -1) {
    writer.write(buf, 0, read);
  }
  reader.close();
  writer.close();

  assertExpectedString(writer.toString());
}
 
Example 17
Project: Project-Tauro   File: CoshipScraper.java   Source Code and License Vote up 4 votes
private List<Map<String, String>> fetchDetails(String bssid) throws IOException {
  String url = hostUrl + "goform/wirelessGetSecurity";
  HttpClient httpClient = new DefaultHttpClient();
  HttpPost post = new HttpPost(url);

  //add reuqest header
  post.setHeader("User-Agent", USER_AGENT);
  post.setHeader("Content-type", "UTF-8");
  post.setHeader("Authorization", "Basic " + base64Login);

  List<NameValuePair> urlParameters = new ArrayList<>();
  urlParameters.add(new BasicNameValuePair("n/a", ""));
  // Send post request

  post.setEntity(new UrlEncodedFormEntity(urlParameters));
  System.out.println("\nSending 'POST' request to URL : " + url);
  //System.out.println("Post parameters : " + post.getEntity());
  HttpResponse response = httpClient.execute(post);

  System.out.println("Response Code : " + response.getStatusLine().getStatusCode());

  System.out.println(response.getEntity().getContentLength() + " bytes received.");
  System.out.println(response.getEntity().isChunked() + " chunked.");
  System.out.println(response.getEntity().isStreaming() + " streaming.");
  System.out.println(response.getEntity().getContentType());
  System.out.println(response.getEntity().getContentEncoding());

  int in;
  StringBuilder result = new StringBuilder();
  BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

  while ((in = rd.read()) != -1) {
    result.append((char) in);
    System.out.println(in);
  }

  System.out.println(result.toString());
  String str = result.toString();

  String[] allStr = str.split("\n");

  List<Map<String, String>> wifiDataList = new ArrayList<>();

  for (int i = 0; i < allStr.length - 1; i++) {
    Map<String, String> wifiData = new HashMap<>();
    String[] fields_str = allStr[i + 1].split("\r");

    wifiData.put("BSSID", bssid);
    wifiData.put("SSID", fields_str[0]);
    wifiData.put("AuthType", fields_str[2]);
    wifiData.put("Encryption", fields_str[3]);
    wifiData.put("key", fields_str[13]);

    wifiDataList.add(wifiData);
  }

  List<Map<String, String>> remove = new ArrayList<>();

  for (Map<String, String> m : wifiDataList) {
    Logger.info(host + ": Found SSID: " + m.get("SSID"));

    Logger.info(host + ": Found AuthType: " + m.get("AuthType"));
    Logger.info(host + ": Found Encryption: " + m.get("Encryption"));

    if (m.get("key") == null) {
      remove.add(m);
      Logger.error("Non-WPA found. Code for this shit!");
    }
    Logger.info(host + ": Found key: " + m.get("key"));
  }

  wifiDataList.removeAll(remove);

  return wifiDataList;
}
 
Example 18
Project: dataflow-opinion-analysis   File: TextWithProperties.java   Source Code and License Vote up 4 votes
private void initialize(String s) throws Exception {
	
	boolean done = false;
	boolean lineConsumed = false;
	BufferedReader reader = new BufferedReader(new StringReader(s));
	String line = null;
	
	// Read the properties first. One property per line, divided by =. Comment lines needs to start with #
	
	while(!done) {
		line = reader.readLine();
		
		if (line == null) {
			done = true;
			continue;
		}
		
		if (line.startsWith("#") || line.equals("")) {
			lineConsumed = true;
			continue;
		}
		
		int equalsPos = line.indexOf("=");
		
		if (equalsPos >= 0) {
			String leftOf = line.substring(0, equalsPos).toLowerCase();
			String rightOf = line.substring(equalsPos+1, line.length());
			lineConsumed = true;
			this.properties.put(leftOf,rightOf);
		} else{
			done = true;
			lineConsumed = false;
		}
	}
	char[] caRest = new char[s.length()]; // we don't know the size beforehand, but it can't be longer than the original s string
	reader.read(caRest);
	String rest = (new String(caRest)).trim();
	String remainingText = (!lineConsumed && line!=null?line+"\n":"") + rest;
	this.text = remainingText;
	
	
}
 
Example 19
Project: boohee_v5.6   File: a.java   Source Code and License Vote up 4 votes
private void a(BufferedReader bufferedReader, BufferedWriter bufferedWriter, Pattern pattern) {
    char[] cArr = new char[4096];
    int read = bufferedReader.read(cArr);
    boolean z = false;
    while (read != -1 && !z) {
        boolean z2;
        String str = new String(cArr, 0, read);
        Matcher matcher = pattern.matcher(str);
        int i = 0;
        int i2 = 0;
        while (i < read && matcher.find(i)) {
            i = matcher.start();
            String substring = str.substring(i, this.c.length() + i);
            if (this.e) {
                if (substring.compareTo(this.d) > 0) {
                    z2 = true;
                    break;
                }
            } else if (substring.compareTo(this.c) >= 0) {
                this.e = true;
                i2 = i;
            }
            int indexOf = str.indexOf(10, i);
            i = indexOf != -1 ? i + indexOf : i + this.c.length();
        }
        i = read;
        z2 = z;
        if (this.e) {
            i -= i2;
            this.f += i;
            if (z2) {
                bufferedWriter.write(cArr, i2, i);
                return;
            }
            bufferedWriter.write(cArr, i2, i);
            if (this.f > this.g) {
                return;
            }
        }
        z = z2;
        read = bufferedReader.read(cArr);
    }
}
 
Example 20
Project: Equella   File: CsvReader.java   Source Code and License Vote up 4 votes
/**
 * @exception IOException Thrown if an error occurs while reading data from
 *                the source stream.
 */
private void checkDataLength() throws IOException
{
	if( !initialized )
	{
		if( fileName != null )
		{
			inputStream = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), charset),
				MAX_FILE_BUFFER_SIZE);
		}

		charset = null;
		initialized = true;
	}

	updateCurrentValue();

	if( userSettings.captureRawRecord && dataBuffer.count > 0 )
	{
		if( rawBuffer.buffer.length - rawBuffer.position < dataBuffer.count - dataBuffer.lineStart )
		{
			int newLength = rawBuffer.buffer.length
				+ Math.max(dataBuffer.count - dataBuffer.lineStart, rawBuffer.buffer.length);

			char[] holder = new char[newLength];

			System.arraycopy(rawBuffer.buffer, 0, holder, 0, rawBuffer.position);

			rawBuffer.buffer = holder;
		}

		System.arraycopy(dataBuffer.buffer, dataBuffer.lineStart, rawBuffer.buffer, rawBuffer.position,
			dataBuffer.count - dataBuffer.lineStart);

		rawBuffer.position += dataBuffer.count - dataBuffer.lineStart;
	}

	try
	{
		dataBuffer.count = inputStream.read(dataBuffer.buffer, 0, dataBuffer.buffer.length);
	}
	catch( IOException ex )
	{
		close();

		throw ex;
	}

	// if no more data could be found, set flag stating that
	// the end of the data was found

	if( dataBuffer.count == -1 )
	{
		hasMoreData = false;
	}

	dataBuffer.position = 0;
	dataBuffer.lineStart = 0;
	dataBuffer.columnStart = 0;
}