4.5.3.2 FlileInputStream和FileOutputStream类

h4 { margin-top: 0.49cm; margin-bottom: 0.51cm; line-height: 156%; page-break-inside: avoid; }h4.western { font-family: "Arial",sans-serif; font-size: 14pt; }h4.cjk { font-family: "黑体","SimHei"; font-size: 14pt; }h4.ctl { font-family: "DejaVu Sans"; font-size: 14pt; }p { margin-bottom: 0.21cm; }


FlileInputStream FileOutputStream 分别用来创建磁盘文件的输入流和输出流对象,通过他们的构造函数来指定文件路径和文件名

创建FileInputStream 类时 指定的文件应该是存在可读的

创建FileOutputStream 实例对象时如果文件已存在 那么文件将会被覆盖

对同一个磁盘文件创建FileInputStream 的来两种方式

  1. FileInputStream fileInputStream = new FileInputStream( " 文件名 " );

  2. File file = new File( " 文件名 " );

FileInputStream fileInputStream = new FileInputStream( file );

用第二种方式在写入之前可以判断文件是否存在 之类的

创建 FileOutputStrem 实例对象的时候,可以指定还不存在的文件 但不能指定已被其他程序打开的程序文件

 

FileOutputStream 写入文件的方法

FileOutputStream fileOutputStream = new FileOutputStream( "src/cn/itcast/ioc/hello.txt" );

fileOutputStream.write( "wangxiang" .getBytes());

 

FileInputStream 读取文件的方法

File file = new File( "src/cn/itcast/ioc/hello.txt" );

FileInputStream fileInputStream = new FileInputStream(file);

byte [] buf = new byte [1024];

int len = 0;

len = fileInputStream.read(buf);

System. out .println( new String( new String(buf,0,len)));

注意 如果打印文件的时候 把全部的字节数组转换为字符串会出现乱码 ,所以用 string 另外一个构造方法 转换固定的长度

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值