Reading bytes of data

From http://www.java-tips.org/java-se-tips/java.io/reading-a-file-into-a-byte-array.html

http://www.cafeaulait.org/course/week10/06.html

 

The basic read() method of the InputStream class reads a single unsigned byte of data and returns the int value of the unsigned byte. This is a number between 0 and 255. If the end of stream is encountered, it returns -1 instead; and you can use this as a flag to watch for the end of stream.

public abstract int read() throws IOException

Here's a simple program that echoes back what the user types at the command line. The byte is cast to its equivalent in the ISO Latin-1 character set before being printed. This program does not properly handle Unicode. In general, input and output streams do not properly handle Unicode data. Therefore you should use them only for raw data and use the java.io.Reader and java.io.Writer classes for text data, especially non-ASCII data.

/* Note that as a general rule on most platforms characters
are only sent to System.in a line at a time, not as each character
is typed. This allows the user to backspace over mistakes and
correct them.  Java does not allow you to put the console into
"raw" mode.  */
import java.io.*;
public class Echo {
public static void main(String[] args) {
try {
echo(System.in);
}
catch (IOException ex) {
System.err.println(ex);
}
}
public static void echo(InputStream in) throws IOException {
while (true) {
// Notice that although a byte is read, an int
// with value between 0 and 255 is returned.
// Then this is converted to an ISO Latin-1 char
// in the same range before being printed.
int i = in.read();
// -1 is returned to indicate the end of stream
if (i == -1) break;
// without the cast a numeric string like "65"
// would be printed instead of the character "A"
char c = (char) i;
System.out.print(c);
}
System.out.println();
}
}
 
 





























转载于:https://www.cnblogs.com/aspxphpjsprb/archive/2009/01/05/1368650.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值