1 package com.test;
2
3 import java.io.File;
4 import java.io.FileInputStream;
5 import java.io.FileNotFoundException;
6 import java.io.FileOutputStream;
7 import java.io.IOException;
8 import java.io.InputStream;
9 import java.io.OutputStream;
10 /**
11 * 流是一组有顺序的,有起点和重点的字节集合,是对数据传输的总称和抽象。及数据在两设备之间的传输称为流。
12 * 流的本质是数据传输,根据数据传输特性将流抽象为各种类,以便更直观的进行数据操作。
13 * 处理数据类型:字节流和字符流
14 * 流向不同 :输入流和输出流
15 * @author lcdn
16 *
17 */
18 public class TestByteSream {
19 /**
20 * 字节输入流:从文件向程序中读入数据---读
21 * InputStream类:此抽象类表示字节输入流的所有类的超类
22 * 从文件系统的某个文件中获得输入字节用FileInputStream
23 */
24 public static void read(){
25 File file = new File("e://b.txt");
26 try {
27 //针对文件建立输入流
28 InputStream in = new FileInputStream(file);
29 byte[] bytes = new byte[1024*1024];//定义一个字节数组
30 int len = -1;//每次真实读取的长度
31 StringBuffer buf = new StringBuffer();
32 while((len = in.read(bytes))!=-1){//表示有可读数据
33 buf.append(new String(bytes,0,len));
34 }
35 in.close();
36 System.out.println(buf);
37 } catch (FileNotFoundException e) {
38 // TODO Auto-generated catch block
39 e.printStackTrace();
40 } catch (IOException e) {
41 // TODO Auto-generated catch block
42 e.printStackTrace();
43 }
44 }
45 /**
46 * 字节输出流:从程序向文件中输出数据---写
47 * OutputStream类:此抽象类是输出字节流的所有类的超类,输出流接收输出字节并将这些字节
48 * 发送到InoutStream类的某个接收器。
49 * 要向文件中输出使用FileOutputStream
50 */
51 public static void write(){
52 File file = new File("e://b.txt");
53 if(!file.exists()){
54 try {//文件可能不可写
55 file.createNewFile();
56 } catch (IOException e) {
57 // TODO Auto-generated catch block
58 e.printStackTrace();
59 }
60 }else{
61 try {
62 /**
63 * 针对文件建立输出流
64 * FileOutStream构造方法之第二参数“true”表示在原有文件的内容上继续写入数据不覆盖,反之
65 */
66 OutputStream out = new FileOutputStream(file, true);
67 String info = "Android之Java基础第二篇!";
68 //向文件中写入数据
69 out.write(info.getBytes());
70 //关闭输出流
71 out.close();
72 } catch (FileNotFoundException e) {
73 // TODO Auto-generated catch block
74 e.printStackTrace();
75 } catch (IOException e) {
76 // TODO Auto-generated catch block
77 e.printStackTrace();
78 }
79 }
80 }
81 public static void main(String[] args){
82 //write();
83 read();
84 }
85 }