JAVA 基础之字节流

FileInputStream:当读取到文件的末尾时,当读到文件末尾时,read()会返回-1,根据这个返回值来判断是否已经读取到文件末尾。

当没有读到文件末尾时,read()返回的是实际读取的字节数。

package com.filestream;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class fileInputstreamDemo {

	public static void main(String[] args) {
		int fileLen = 0;
		
		FileInputStream fis;
		try {
			 
			fis = new FileInputStream("c:\\filetest\\file\\speech.txt");
			/*
			 * 读取方法1
			int temp = 0;
			while ((temp = fis.read()) != -1) {
				System.out.print((char)temp);
				fileLen++;
			}
                        fis.close();
			*/
			
			//读取方法2:
			byte []temp = new byte[26];
			fis.read(temp);
			System.out.println(new String(temp));
			fileLen = temp.length;
                        fis.close();
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		System.out.println("file lenth : " + fileLen);
			
		
	}

}

FileOutputStream and BufferedOutputStream:

package com.filestream;

import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class bufferstreamDemo {

	public static void main(String[] args) {
		try {
			FileOutputStream fos = new FileOutputStream("c:\\filetest\\file\\one.txt");
			FileOutputStream fos2 = new FileOutputStream("c:\\filetest\\file\\two.txt");
			BufferedOutputStream bos = new BufferedOutputStream(fos2);
			long oneStarttime = System.currentTimeMillis();
			int temp1 = 0;
			while(temp1<100000) {
				fos.write('a');
				temp1++;
//				System.out.println("正在写one.txt: "+ temp1);
			}
			long oneEndTime = System.currentTimeMillis();
			System.out.println("one.txt不使用缓存流来写,用时为: " + (oneEndTime - oneStarttime));
			
			int temp2 = 0; 
			long oneStarttime2 = System.currentTimeMillis();
			while(temp2<100000) {
				bos.write('a');
				temp2++;
//				System.out.println("正在写two.txt: "+ temp2);
//				bos.flush();
			}
			long oneEndTime2 = System.currentTimeMillis();
			System.out.println("two.txt使用缓存流来写,用时为: " + (oneEndTime2 - oneStarttime2));
			
		} catch (FileNotFoundException e) {
			
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值