字节输入流:
自己的理解:使用inputStream,输入流:也就是要从文件里面读出内容到内存(电脑控制台),也就是说对于内存(电脑控制台)来说就是输入.
下面的代码的说明的内容:
首先是一个字节一个字节的读取:
1.创建了多个对象来接收;
2.通过循环,来循环读;
3.读指定长度 byte [] b = new byte[5] (字节数组).
一些代码说明:
public class TestInputStream {
public static void main(String[] args) throws Exception {
//method2();
method3();
}
public static void method1() throws Exception{
// InputStream 是抽象类,只能通过子类创建
InputStream is = new FileInputStream("d:\\aaaa.txt");
// 读数据
int num1=is.read(); // 读取一个字节 我abcdef 1个字符=2个字节 ,通常一个汉字需要读两次
int num2 = is.read();
int num3 = is.read();
System.out.println(num1);
System.out.println(num2);
System.out.println(num3);
// 关闭流
is.close();
}
/**
* 通过字节数组 读取
* @throws Exception
*/
public static void method2() throws Exception{
InputStream is = new FileInputStream(new File("d://aaaa.txt"));
// 字节数组
byte [] b = new byte[5];
// 将数据存放在b中
/*int length = is.read(b); // 返回 实际读取的长度
System.out.println(new String(b)+"----"+length);
length = is.read(b);
System.out.println(Arrays.toString(b)+"----"+length);
length = is.read(b);
System.out.println(Arrays.toString(b)+"----"+length);
length = is.read(b);
System.out.println(Arrays.toString(b)+"==="+length);
*/
//循环读
StringBuffer sb = new StringBuffer();
int len = is.read(b);
while(len!=-1){
sb.append(new String(b));
//继续读
len=is.read(b);
}
System.out.println("结果:"+sb);
}
/**
* 读指定长度
* @throws Exception
*/
public static void method3() throws Exception{
InputStream is = new FileInputStream(new File("d:\\aaaa.txt"));
//读指定长度
byte [] b = new byte[5];
// 跳过2个字节
is.skip(5);
System.out.println("剩余字节数:"+is.available());
/* is.read(b, 0, 3);
System.out.println(new String(b));*/
StringBuffer sb = new StringBuffer();
int len = 0 ;
while((len=is.read(b))!=-1){
sb.append(new String(b, 0, len)); // 将数组中的指定长度 转成字符串
}
System.out.println("2剩余字节数:"+is.available());
System.out.println("内容:"+sb);
is.close();
}
}