Java 输入输出流InPutStream及OutPutStream

Java.io.InputStream 输入流

Java.io.OutputStream 输出流

Java.io.FileInputStream(File)  FIS

public class InputStreamDemo {

	public static void main(String[] args) throws IOException {
		ReadByBufferDemo();
	}
	public static void ReadDemo() throws IOException{
		InputStream in=new FileInputStream("demo");
		//读取文件的一个byte,无符号填充到int低8位,返回0x00000000~0x000000ff,如果读到文件尾,返回-1
		int a=in.read();
		while((a=in.read())!=-1){//循环读取,直到文件尾
			System.out.println(a);
		}
	}
	public static void ReadByBufferDemo() throws IOException{
		InputStream in=new FileInputStream("demo");
		byte[] buffer=new byte[10];
		//a的范围1~10,若为-1表示到文件尾了
		int a;
		while((a=in.read(buffer))!=-1){
			System.out.println(toHexString(buffer));
		}
	}
	private static String toHexString(byte[] buffer) {
		StringBuilder str=new StringBuilder();
		for (int i = 0; i < buffer.length; i++) {
			int a=buffer[i]&0xff;//byte转Int时,如果为负数,前面将补1,用掩码运算,保卫部
			str.append(Integer.toHexString(a)+" ");
		}
		return str.toString();
	}
}

Java.io.FileOutputStream(File) FOS

public class OutputStreamDemo {

	public static void main(String[] args) throws IOException {
		/*
		 * 顺序写 write
		 */
		OutputStream out= new FileOutputStream("demo");
		out.write(0xbb);
		out.write(0xd3);
		out.write(0xd6);
		out.write(0xd0);
		out.write(0xbf);
		out.write(0xda);
		byte[] buffer={98,99,(byte)0xd6,(byte)0xd0};
		out.write(buffer,0,4);//将buffer偏移0处的4个字节写入文件demo
		out.write("试试吧".getBytes("GBK"));//写入文件
		out.close();
	}

Java.io.BufferedInputStream(InputStream) BIS


Java.io.BufferedOutputStream(OutputStream) BOS

public static void main(String[] args) throws IOException{
  //打开带有输入缓冲的流,当读取流中的数据时(In.read()),BIS会将数据成块读取到内存数组,再顺序读取出来。
  InputStream In=new BufferedInputStream(new FileInputStream("demo"));//In类似于一个水缸,水来自demo文件
  int b=In.read();//一次读一块进来,顺序赋值
  System.out.print(b);
  In.close();
  //BufferedOutputStream可以为任意流提供输出缓冲区管理,写出的数据先缓冲到BufferedOutputStream的byte数组中,在缓冲区满了之后,一次性写入到目标流里面
  OutputStream Out=new BufferedOutputStream(new FileOutputStream("demo"));//此步骤并未真正写入硬盘,只是存储在缓冲区中
  Out.write(0x41);
  Out.flush();//将缓冲区的流写入到硬盘
  Out.close();//关闭一个流时,强行将缓冲区数据写入硬盘,默认调用flush();
 }





你可能感兴趣的:(JAVA基础)