【IO流】FileInputStream,FileOutputStream读写文件

FileInputStream,FileOutputStream(文件字节输入输出流)读写文件

注:IO流使用完之后 记得关闭,释放资源

/**
 * FileOutputStream FileInputStream Test
 * 
 * @author xiazhang
 * @date   2017-6-4
 */
public class FileOutInputStreamTest {

	/**
	 * 读文件
	 */
	private static void readFile(File file){
		try {
			FileInputStream fis = new FileInputStream(file);
			
			//每次读取一个字节
			/*int content = fis.read();
			//content != -1 表示读到结束的标记
			while(content != -1){
				System.out.print((char)content);
				content = fis.read();
			}*/
			
			
			/*int num = 1;//读取次数
			byte[] b = new byte[20];
			//从此输入流中将最多 b.length 个字节的数据读入一个 byte 数组中
			//每次读取20个字节到byte数组中
			//返回的int表示读到此数组中的实际长度
			int len = fis.read(b);
			while(len != -1){
				System.out.print(new String(b,0,len));
				len = fis.read(b);
				if(len != -1){
					num++;
				}
			}
			//结果:共读取5次
			System.out.println("读取次数:"+num);*/
			
			
			
			int num = 1;//读取次数
			byte[] b = new byte[20];
			//从此输入流中将最多 5 个字节的数据读入一个 byte 数组中
			int len = fis.read(b, 1, 5);
			while(len != -1){
				System.out.println(new String(b,1,len));
				len = fis.read(b, 1, 5);
				if(len != -1){
					num ++;
				}
			}
			//结果:共读取17次
			System.out.println("读取次数:"+num);
			
			//流必须关闭  释放资源
			fis.close();
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 写入文件
	 */
	private static void writeFile(File file){ 
		try {
			FileOutputStream fos = new FileOutputStream(file);
			//写入字节
			fos.write(97);
			fos.write(98);
			fos.write(99);
			//关闭流  释放资源
			fos.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO: handle exception
		}
	}
	
	
	
	public static void main(String[] args) {
		File file = new File("fileTest3.txt");
		if(!file.exists()){//检查文件是否存在
			/*try {
				file.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}*/
			System.out.println(file.getName()+"不存在!");
		}else{
			readFile(file);
			writeFile(file);
		}
		
	}

}








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值