字节流与字符流

有关于流的概念:
程序中的所有数都是以流的方式进行传输或或保存的,保存的内容嗾使字节文件,程序需要数据的时候 要使用输入流读取数据,程序需要将一些数据保存的时候没救要用输出流来实现。

字节流的输出依赖OutputStream、输入依赖InputStream
字符流的输出主要使用Writer类、输入流依赖Reader类

1、字节流在硬盘上创建文件,并写入内容:

1 import java.io.File;
2 import java.io.FileOutputStream;
3 import java.io.IOException;
4 import java.io.OutputStream;
5
6 public class Test11 {
7 public static void main(String[] args) throws IOException {
8 File f = new File(“d:” + File.separator+”test.txt”);
9 OutputStream out=new FileOutputStream(f);//如果文件不存在会自动创建
10 String str=”Hello World”;
11 byte[] b=str.getBytes();
12 out.write(b);//因为是字节流,所以要转化成字节数组进行输出
13 out.close();
14 }
15 }

2、字节输入流读取文件内容

1 import java.io.File;
2 import java.io.FileInputStream;
3 import java.io.IOException;
4 import java.io.InputStream;
5
6 public class Test12 {
7 public static void main(String[] args) throws IOException {
8 File f = new File(“d:” + File.separator+”test.txt”);
9 InputStream in=new FileInputStream(f);
10 byte[] b=new byte[1024];
11 int len=in.read(b);
12 in.close();
13 System.out.println(new String(b,0,len));
14 }
15 }

3、字符流在硬盘上创建文件,并写入内容:
1 import java.io.File;
2 import java.io.FileWriter;
3 import java.io.IOException;
4 import java.io.Writer;
5
6 public class Test16 {
7 public static void main(String[] args) throws IOException {
8 File f = new File(“d:” + File.separator+”test.txt”);
9 Writer out=new FileWriter(f);
10 String str=”Hello World”;
11 out.write(str);
12 out.close();
13 }
14 }

4、字节输入流读取文件内容
1 import java.io.File;
2 import java.io.FileReader;
3 import java.io.IOException;
4 import java.io.Reader;
5
6 public class Test18 {
7 public static void main(String[] args) throws IOException {
8 File f = new File(“d:” + File.separator+”test.txt”);
9 Reader input=new FileReader(f);
10 char[] c=new char[1024];
11 int len=input.read(c);
12 input.close();
13 System.out.println(new String(c,0,len));
14 }
15 }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值