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

The following examples show how to use java.io.BufferedReader#read() . 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: BufferedReaderDemo.java    From code with Apache License 2.0 6 votes vote down vote up
@Test
public void testCharRead() throws IOException {
    // 1、创建字符缓冲输入流对象
    BufferedReader br = new BufferedReader(new FileReader("bw.txt"));

    // 2、读输入流
    // 方式1
    // int ch = 0;
    // while ((ch = br.read()) != -1) {
    // System.out.print((char) ch);
    // }

    // 方式2
    char[] chars = new char[1024];
    int len;
    while ((len = br.read(chars)) != -1) {
        System.out.print(new String(chars, 0, len));
    }

    // 3、释放资源
    br.close();
}
 
Example 2
Source File: SQLOutputImpl.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 3
Source File: ResultSetHelper.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
public static String convertCharArrayToString(BufferedReader reader, int size){
	//char[] charArray= new char[size];
  StringBuilder sb = new StringBuilder();
  sb.append('{');
  int readChars;
  
	try {
	  while ((readChars = reader.read()) != -1) {
	    sb.append(readChars + ", ");
	  }  		
	} catch (Exception e) {
		throw new TestException("could not read in the charaters "
				+ TestHelper.getStackTrace(e));
	}
	
	sb.deleteCharAt(sb.lastIndexOf(","));
	sb.append('}');
	return sb.toString();
}
 
Example 4
Source File: Io.java    From openxds with Apache License 2.0 6 votes vote down vote up
static public String stringFromBufferedReader(BufferedReader in) throws IOException {
	StringBuffer buf = new StringBuffer();

	char[] chars = new char[2048];

	int count;

	count = in.read(chars, 0, chars.length);
	while(count > -1) {
		if (count > 0)
			buf.append(chars, 0, count);
		count = in.read(chars, 0, chars.length);
	}

	return buf.toString();
}
 
Example 5
Source File: InternalClobTest.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Transfers data from the source to the destination.
 */
public static long transferData(Reader src, Writer dest, long charsToCopy)
        throws IOException {
    BufferedReader in = new BufferedReader(src);
    BufferedWriter out = new BufferedWriter(dest, BUFFER_SIZE);
    char[] bridge = new char[BUFFER_SIZE];
    long charsLeft = charsToCopy;
    int read;
    while ((read = in.read(bridge, 0, (int)Math.min(charsLeft, BUFFER_SIZE))) > 0) {
        out.write(bridge, 0, read);
        charsLeft -= read;
    }
    in.close();
    // Don't close the stream, in case it will be written to again.
    out.flush();
    return charsToCopy - charsLeft;
}
 
Example 6
Source File: SQLOutputImpl.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Writes a stream of ASCII characters to this
 * <code>SQLOutputImpl</code> object. The driver will do any necessary
 * conversion from ASCII 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 writeAsciiStream(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 7
Source File: WebSessionTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @param port Port.
 * @param addCookie Whether to add cookie to request.
 * @throws IOException In case of I/O error.
 */
private static void doRequest(int port, boolean addCookie) throws IOException {
    URLConnection conn = new URL("http://localhost:" + port + "/ignitetest/test").openConnection();

    if (addCookie)
        conn.addRequestProperty("Cookie", "JSESSIONID=" + SES_ID.get());

    conn.connect();

    BufferedReader rdr = new BufferedReader(new InputStreamReader(conn.getInputStream()));

    if (!addCookie)
        SES_ID.set(rdr.readLine());
    else
        rdr.read();
}
 
Example 8
Source File: HlsPlaylistParser.java    From Telegram-FOSS with GNU General Public License v2.0 5 votes vote down vote up
private static int skipIgnorableWhitespace(BufferedReader reader, boolean skipLinebreaks, int c)
    throws IOException {
  while (c != -1 && Character.isWhitespace(c) && (skipLinebreaks || !Util.isLinebreak(c))) {
    c = reader.read();
  }
  return c;
}
 
Example 9
Source File: JsCommentGeneratorTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static String readFileAsString(File file) throws java.io.IOException {
    StringBuilder fileData = new StringBuilder(1000);
    BufferedReader reader = new BufferedReader(new FileReader(file));
    char[] buf = new char[1024];
    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();
    return fileData.toString();
}
 
Example 10
Source File: ValidateLicAndNotice.java    From systemds with Apache License 2.0 5 votes vote down vote up
/**
 * This will return the content of file.
 *
 * @param	file is the parameter of type File from which contents will be read and returned.
 * @return 	Returns the contents from file in String format.
 */
private static String readFile(File file) throws java.io.IOException {
	StringBuffer fileData = new StringBuffer();
        BufferedReader reader = new BufferedReader(new FileReader(file));
	char[] buf = new char[1024];
	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();
	return fileData.toString();
}
 
Example 11
Source File: ClobTest.java    From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 5 votes vote down vote up
private String toString(Reader reader) throws IOException {
    BufferedReader bufferedReader = new BufferedReader( reader);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    int result = bufferedReader.read();

    while(result != -1) {
        byteArrayOutputStream.write((byte) result);
        result = bufferedReader.read();
    }

    return byteArrayOutputStream.toString();
}
 
Example 12
Source File: StreamsHangup.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static String readStream(InputStream is) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    char buf[] = new char[4096];
    int cnt = 0;
    while ((cnt = reader.read(buf)) != -1) {
        String text = String.valueOf(buf, 0, cnt);
        sb.append(text);
    }
    reader.close();
    return sb.toString();
}
 
Example 13
Source File: ProcessMenuCommand.java    From directory-fortress-core with Apache License 2.0 5 votes vote down vote up
void processEncryptManagerFunction()
{
    BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) );
    boolean done = false;
    int input;

    try
    {
        while ( !done )
        {
            showEncryptFunctionMenu();
            input = br.read();
            switch ( input )
            {
                case '1':
                    encryptConsole.encrypt();
                    break;
                case '2':
                    encryptConsole.decrypt();
                    break;
                case 'q':
                case 'Q':
                    done = true;
                    break;
                default:
                    break;
            }
        }
    }
    catch ( Exception e )
    {
        LOG.error( "Exception caught in processEncryptManagerFunction = " + e );
    }
}
 
Example 14
Source File: StreamUtil.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Retrieves the content from an input stream using a specific charset.
 * 
 * @param stream
 *            the input stream
 * @param charset
 *            the charset
 * @return the content
 * @throws IOException
 */
public static String readContent(InputStream stream, String charset) throws IOException
{
	if (stream == null)
	{
		return null;
	}

	BufferedReader reader = getBufferedReader(stream, charset);
	try
	{
		StringBuilder buffer = new StringBuilder();
		char[] readBuffer = new char[2048];
		int n = reader.read(readBuffer);
		while (n > 0)
		{
			buffer.append(readBuffer, 0, n);
			n = reader.read(readBuffer);
		}
		return buffer.toString();
	}
	finally
	{
		try
		{
			reader.close();
		}
		catch (IOException e)
		{
			// ignores
		}
	}
}
 
Example 15
Source File: Utils.java    From AppAuth-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Read a string from an input stream.
 */
public static String readInputStream(InputStream in) throws IOException {
    if (in == null) {
        throw new IOException("Input stream must not be null");
    }

    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    char[] buffer = new char[INITIAL_READ_BUFFER_SIZE];
    StringBuilder sb = new StringBuilder();
    int readCount;
    while ((readCount = br.read(buffer)) != -1) {
        sb.append(buffer, 0, readCount);
    }
    return sb.toString();
}
 
Example 16
Source File: Lines.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public void testInterlacedRead() throws IOException {
    MockLineReader r = new MockLineReader(10);
    BufferedReader br = new BufferedReader(r);
    char[] buf = new char[5];
    Stream<String> s = br.lines();
    Iterator<String> it = s.iterator();

    br.read(buf);
    assertEquals(new String(buf), "Line ");
    assertEquals(it.next(), "1");
    try {
        s.iterator().next();
        fail("Should failed on second attempt to get iterator from s");
    } catch (IllegalStateException ise) {}
    br.read(buf, 0, 2);
    assertEquals(new String(buf, 0, 2), "Li");
    // Get stream again should continue from where left
    // Only read remaining of the line
    br.lines().limit(1L).forEach(line -> assertEquals(line, "ne 2"));
    br.read(buf, 0, 2);
    assertEquals(new String(buf, 0, 2), "Li");
    br.read(buf, 0, 2);
    assertEquals(new String(buf, 0, 2), "ne");
    assertEquals(it.next(), " 3");
    // Line 4
    br.readLine();
    // interator pick
    assertEquals(it.next(), "Line 5");
    // Another stream instantiated by lines()
    AtomicInteger line_no = new AtomicInteger(6);
    br.lines().forEach(l -> assertEquals(l, "Line " + line_no.getAndIncrement()));
    // Read after EOL
    assertFalse(it.hasNext());
}
 
Example 17
Source File: NetworkProxyServerConnection.java    From Ardulink-1 with Apache License 2.0 4 votes vote down vote up
@Override
public void run() {
	try {
		outputStream = socket.getOutputStream();
		printWriter = new PrintWriter(outputStream, true);
		
		inputStream = socket.getInputStream();
		bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
		
		String inputLine = bufferedReader.readLine();
		while (!closed && !handshakeComplete) {
			processInput(inputLine);
			if(!closed && !handshakeComplete) {
				inputLine = bufferedReader.readLine();
			}
           }
		if(!closed) {
			int dataReceived = bufferedReader.read();
			while (dataReceived != -1) {
				String data = String.valueOf((char)dataReceived);
				// System.out.print(data);
				writeSerial(data);
				dataReceived = bufferedReader.read();
            }			
		}
	} catch (IOException e) {
	}
	finally {
		logger.info("{} connection closed.", socket.getRemoteSocketAddress());
		closed = true;
		if(link != null) {
			link.removeRawDataListener(this);
			NetworkProxyServer.disconnect(link.getName());
		}
		try {
			socket.close();
		} catch (IOException socketClosingExceptionTry) {
		}
		link = null;
		socket = null;
		bufferedReader = null;
		inputStream = null;
		printWriter = null;
		outputStream = null;
		closed = true;
	}
}
 
Example 18
Source File: ZipCompress.java    From java-core-learning-example with Apache License 2.0 4 votes vote down vote up
private static void zipFiles(String[] fileNames)
        throws IOException {
    // 获取zip文件输出流
    FileOutputStream f = new FileOutputStream("test.zip");
    // 从文件输出流中获取数据校验和输出流,并设置Adler32
    CheckedOutputStream csum = new CheckedOutputStream(f,new Adler32());
    // 从数据校验和输出流中获取Zip输出流
    ZipOutputStream zos = new ZipOutputStream(csum);
    // 从Zip输出流中获取缓冲输出流
    BufferedOutputStream out = new BufferedOutputStream(zos);
    // 设置Zip文件注释
    zos.setComment("测试 java zip stream");
    for (String file : fileNames) {
        System.out.println("写入文件: " + file);
        // 获取文件输入字符流
        BufferedReader in =
                new BufferedReader(new FileReader(file));
        // 想Zip处理写入新的文件条目,并流定位到数据开始处
        zos.putNextEntry(new ZipEntry(file));
        int c;
        while ((c = in.read()) > 0)
            out.write(c);
        in.close();
        // 刷新Zip输出流,将缓冲的流写入该流
        out.flush();
    }
    // 文件全部写入Zip输出流后,关闭
    out.close();

    // 输出数据校验和
    System.out.println("数据校验和: " + csum.getChecksum().getValue());
    System.out.println("读取zip文件");
    // 读取test.zip文件输入流
    FileInputStream fi = new FileInputStream("test.zip");
    // 从文件输入流中获取数据校验和流
    CheckedInputStream csumi = new CheckedInputStream(fi,new Adler32());
    // 从数据校验和流中获取Zip解压流
    ZipInputStream in2 = new ZipInputStream(csumi);
    // 从Zip解压流中获取缓冲输入流
    BufferedInputStream bis = new BufferedInputStream(in2);
    // 创建文件条目
    ZipEntry zipEntry;
    while ((zipEntry = in2.getNextEntry()) != null) {
        System.out.println("读取文件: " + zipEntry);
        int x;
        while ((x = bis.read()) > 0)
            System.out.write(x);
    }
    if (fileNames.length == 1)
        System.out.println("数据校验和: " + csumi.getChecksum().getValue());
    bis.close();

    // 获取Zip文件
    ZipFile zf = new ZipFile("test.zip");
    // 获取文件条目枚举
    Enumeration e = zf.entries();
    while (e.hasMoreElements()) {
        // 从Zip文件的枚举中获取文件条目
        ZipEntry ze2 = (ZipEntry) e.nextElement();
        System.out.println("文件: " + ze2);
    }

}
 
Example 19
Source File: TestCodec.java    From hadoop with Apache License 2.0 4 votes vote down vote up
@Test
public void testGzipLongOverflow() throws IOException {
  LOG.info("testGzipLongOverflow");

  // Don't use native libs for this test.
  Configuration conf = new Configuration();
  conf.setBoolean(CommonConfigurationKeys.IO_NATIVE_LIB_AVAILABLE_KEY, false);
  assertFalse("ZlibFactory is using native libs against request",
      ZlibFactory.isNativeZlibLoaded(conf));

  // Ensure that the CodecPool has a BuiltInZlibInflater in it.
  Decompressor zlibDecompressor = ZlibFactory.getZlibDecompressor(conf);
  assertNotNull("zlibDecompressor is null!", zlibDecompressor);
  assertTrue("ZlibFactory returned unexpected inflator",
      zlibDecompressor instanceof BuiltInZlibInflater);
  CodecPool.returnDecompressor(zlibDecompressor);

  // Now create a GZip text file.
  String tmpDir = System.getProperty("test.build.data", "/tmp/");
  Path f = new Path(new Path(tmpDir), "testGzipLongOverflow.bin.gz");
  BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
    new GZIPOutputStream(new FileOutputStream(f.toString()))));

  final int NBUF = 1024 * 4 + 1;
  final char[] buf = new char[1024 * 1024];
  for (int i = 0; i < buf.length; i++) buf[i] = '\0';
  for (int i = 0; i < NBUF; i++) {
    bw.write(buf);
  }
  bw.close();

  // Now read it back, using the CodecPool to establish the
  // decompressor to use.
  CompressionCodecFactory ccf = new CompressionCodecFactory(conf);
  CompressionCodec codec = ccf.getCodec(f);
  Decompressor decompressor = CodecPool.getDecompressor(codec);
  FileSystem fs = FileSystem.getLocal(conf);
  InputStream is = fs.open(f);
  is = codec.createInputStream(is, decompressor);
  BufferedReader br = new BufferedReader(new InputStreamReader(is));
  for (int j = 0; j < NBUF; j++) {
    int n = br.read(buf);
    assertEquals("got wrong read length!", n, buf.length);
    for (int i = 0; i < buf.length; i++)
      assertEquals("got wrong byte!", buf[i], '\0');
  }
  br.close();
}
 
Example 20
Source File: RtspResponseParser.java    From DeviceConnect-Android with MIT License 4 votes vote down vote up
/**
 * RTSP サーバからのレスポンスを解析して {@link RtspResponse} に値を格納します.
 *
 * <p>
 * ヘッダーの要素名は、全て小文字に変換して格納します。<br>
 * ヘッダーを取得する場合には注意してください。
 * </p>
 *
 * @param input レスポンスのストリーム
 * @return RTSP サーバからのレスポンス
 * @throws IOException レスポンスの読み込みに失敗した場合に発生
 */
static RtspResponse parse(BufferedReader input) throws IOException {
    RtspResponse response = new RtspResponse();
    String line;
    Matcher matcher;

    if ((line = input.readLine()) == null) {
        throw new SocketException("Client socket disconnected.");
    }

    if (DEBUG) {
        Log.d(TAG, "RTSP RESPONSE START");
        Log.d(TAG, "  " + line);
    }

    matcher = REGEX_STATUS.matcher(line);
    if (matcher.find()) {
        response.setStatus(RtspResponse.Status.statusOf(Integer.parseInt(matcher.group(1))));
    }

    while ((line = input.readLine()) != null) {
        if (DEBUG) {
            Log.d(TAG, "  " + line);
        }

        if (line.length() > 3) {
            matcher = REGEX_HEADER.matcher(line);
            if (matcher.find()) {
                response.addAttribute(matcher.group(1).trim().toLowerCase(), matcher.group(2).trim());
            }
        } else {
            break;
        }
    }

    String contentLengthStr = response.getAttribute("content-length");
    if (contentLengthStr != null) {
        int contentLength = Integer.parseInt(contentLengthStr);
        if (contentLength > 0) {
            char[] buf = new char[contentLength];
            int offset = 0;
            while (offset < contentLength) {
                offset += input.read(buf, offset, contentLength - offset);
            }
            response.setContent(new String(buf));

            if (DEBUG) {
                Log.i(TAG, "");
                Log.i(TAG, new String(buf));
            }
        }
    }

    return response;
}