java io 写文档_Java IO 读写文件

输入Input  —— 读文件read   网络上传

输出Output ——  写文件write   网络下载

以字节为单位  所有类型的文件  视频文件 音频文件 图像文件 文本文件  —— >抽象类 InputStream OutputStream ——>  实现类 FileInputStream FileOutputStream

以字符为单位   仅限于文本文件——>抽象类 Reader Writer ——>实现类  FileReader FileWriter

类的构造方法

FileOutputStream类的构造方法 - 方法参数  String 或 File

FileOutputStream fos = new FileOutputStream("c:\\a.txt");

File file = new File("c:\\a.txt");

FileOutputStream fos = new FileOutputStream(file,true); //第二个参数 是否append追加续写

FileWriter类的构造方法

FileWriter fw = new FileWriter("c:\\1.txt");

FileInputStream类的构造方法

FileInputStream fis = new FileInputStream("c:\\a.txt");

FileReader类的构造方法

FileReader fr = new FileReader("c:\\1.txt");

类的成员方法

FileOutputStream类的“写”方法

//写1个字节 Java中 ,byte类型的数值范围 -128~127

fos.write(97);//写字节数组

byte[] bytes = {65,66,67,68,69,70};

fos.write(bytes);//写字节数组的一部分,开始索引,写几个

fos.write(bytes, 2, 3);

fos.write("hello\r\n world".getBytes());//String类的getBytes()方法 将字符串转为字节数组

FileInputStream类的“读”方法

int len = fis.read();//每执行一次read() 就自动读取下一字节 切勿多次书写read()

byte[] b = new byte[1024];

int len = fis.read(b);//读到文件末尾的结束符时 read()方法直接返回-1 len 每次读取 真实有效字节的数目 每次读取到的字节存储在字节数组b中

int len = 0;//接受read方法的返回值

while( (len = fis.read()) != -1){

System.out.print((char)len);

}

//创建字节数组

byte[] b = new byte[1024];//每次读取1024字节 即1kb 以提高文件读取的效率

int len = 0;while( (len = fis.read(b)) !=-1){

System.out.print(new String(b,0,len));//String类的 字节数组参数 构造方法

}

FileWriter类的“写”方法

//写1个字符

fw.write(100);

fw.flush();//字符输出流 写数据的时候,必须要运行此刷新缓存的功能//写字符数组

char[] c = {'a','b','c','d','e'};

fw.write(c);

fw.flush();//写字符数组一部分

fw.write(c, 2, 2);

fw.flush();//写字符串

fw.write("hello");

fw.flush();

FileReader类的“读”方法

char[] ch = new char[1024];//字符数组 java中 一个字符占2个byte字节!

int len = 0;while((len = fr.read(ch))!=-1){

System.out.print(new String(ch,0,len));

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值