IO流的相关操作

**  文件字节输入
 * IO流的操作步骤
 * 1.创建源文件
 * 2.选择流
 * 3控制操作
 * 4.释放内存
 * @author Administrator
 *IOInputStream输入流
 */
public class IOInputStreamTest {

	public static void main(String[] args) {
		//1.创建源
		File file = new File("HelloWorld.txt");//必须要有这个文件
		
		//2.选择流
		InputStream io = null;
		try {
			io = new FileInputStream(file);
			//3.控制操作
                        int len = 2;//  接收长度
			byte[] fulsh = new byte[1024];  //进行缓存,每1024字节进行输出
			while((len=io.read(fulsh))!=-1) {
				//把字节数组-->字符串
				String str = new String(fulsh, 0, len);
				System.out.println(str);
			}
		} catch (FileNotFoundException e) {
			
			e.printStackTrace();
		}catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				//4.进行关闭,释放内存
				if(io!=null)  //判断一下,如果源文件为空的时候,进行关闭操作
				io.close();
			} catch (IOException e) {
			
				e.printStackTrace();
			}
		}
		
	}
}
**        文件字节输出
 * IOOutputStream  输出流的测试
 * 
 * IO流的操作步骤
 * 1.创建源
 * 2.选择流
 * 3控制语句
 * 4释放内存
 * @author Administrator
 *OutputStream输出流测试
 */
public class IOOutputStreamTest {
	public static void main(String[] args) {
		//1.创建源
		File file = new File("HelloWorld.txt");    //可以没有此文件,如果没有此文件,系统自动会给你创建出来
		
		//2.选择流
		OutputStream op = null;
		try {
		    op = new FileOutputStream(file);
		    String str = "Hello World";      //被写入的具体内容
		    byte[] flush = str.getBytes();  //字符串-->字节数组
		    op.write(flush, 0, str.length()); //写入到指定位置
		    op.flush();                //刷新此输出流并强制任何缓冲的输出字节被写出。
		    
		} catch (FileNotFoundException e) {
			
			e.printStackTrace();
		}catch (IOException e) {
			
			e.printStackTrace();
		
		}finally {
			try {
			//4.关闭,释放内存
				op.close();
			} catch (IOException e) {
			
				e.printStackTrace();
			}
		}
		
		
		
		
		
	}

}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值