JAVA 字节流使用总结

OutputStream : 
public void write(byte[] b)throws IOException 输出单个字节
public void write(byte[] b)throws IOException 输出全部字节数组
public void write(byte[] b,int off,int len)throws IOException 输出部分字节数组


OutputStream 本身是属于抽象类,如果要想为抽象类进行对象的实例化操作,那么一定要使用抽象类的子类。FileOutputStream是处理文件的。
public FileOutputStream(File file)throws FileNotFoundException 普通输入
public FileOutputStream(File file,boolean append)throws FileNotFoundException 可以追加输入
public class OutputStreamDemo {
	public static void main(String[] args) {
		File file = new File("E:" + File.separator + "demo.txt");
		if(!file.getParentFile().exists()){
			file.getParentFile().mkdirs();
		}
		OutputStream output = null;
		try {
			output = new FileOutputStream(file,true);
			String str="Hello World \r\n";
			byte data[] = str.getBytes();
			//output.write(data);
			output.write(data,2,5);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				output.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}
}



InputStream:
public abstract int read()throws IOException 读取单个字节数
返回值:返回下一个数据的字节,但是如果已经读取到结尾了,返回-1。
public int read(byte[] b)throws IOException 将读取的数据保存在字节数组中。
返回值:返回读取的数据长度,但是如果已经读取到结尾了,返回-1。
public int read(byte[] b,int off,int len)throws IOException 将读取的数据保存在部分字节数组中
返回值:返回读取部分的数据长度,但是如果已经读取到结尾了,返回-1。


InputStream是一个抽象类,用于数据的读取操作。

public FileInputStream(File file)throws FileNotFoundException

public class InputStreamDemo {
	public static void main(String[] args) throws IOException {
		File file = new File("E:" + File.separator + "demo.txt");
		if(file.exists()){
			InputStream input = new FileInputStream(file);
			byte data[] = new byte[1024];
			//方式一:
			//int len = input.read(data);
			//方式二:
/*			int foot = 0;//表示字节数组的操作脚标
			int temp = 0;
			do{
				temp = input.read();
				if(temp != -1){
					data[foot++] = (byte)temp;
				}
			}while(temp != -1);*/
			//方式三:使用最多
			int foot = 0;//表示字节数组的操作脚标
			int temp = 0;
			while((temp = input.read()) != -1){
				data[foot++] = (byte)temp;
			}
			input.close();
			System.out.println(new String(data,0,foot));
		}
	}
	
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值