**输入流:东西读入内存
输出流:东西从内存写到记录存储**
因为我们本身是以记录存储为原点来判读输入和输出的概念,所有会有弄错的时候。
在java中, io流按照java io流的方向可以分为输入流和输出流。
输入流是将资源数据读入到缓冲Buffer中,输出流是将缓冲Buffer中的数据按照指定格式写出到一个指定的位置,所以这两个流一般同时使用,才有意义。
例如你要做文件的上传,你要先用输入流将待上传文件读入缓冲,然后用输出流将文件写出到网络服务器的一个位置,则上传成功;
若是文件下载,则先获得输入流,来读取网络服务器中的一个文件,然后用输出流写到本地的一个文件中;还有例如文件的拷贝,也是先用输入流读再用输出流写出去。
下面的例子是在android开发中一个小案例:
public class MainActivity extends Activity {
EditText et_input;
Button btn_submit, btn_clear;
TextView tv_show;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_input = (EditText) findViewById(R.id.et_Input);
btn_submit = (Button) findViewById(R.id.btn_submit);
btn_clear = (Button) findViewById(R.id.btn_clear);
tv_show = (TextView) findViewById(R.id.tv_show);
btn_submit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
WriteFiles(et_input.getText().toString());
tv_show.setText(readFiles());
}
});
btn_clear.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
et_input.setText("");
}
});
}
/**
* 保存文件:将buffer中的数据输出到物理存储介质上
* 输入流:将数据读入到内存中
* 输出流:将内存中的数据读出到硬盘上
*/
private void WriteFiles(String content) {
// TODO Auto-generated method stub
try {
//相对于程序来讲,是程序输出内容到文件中
FileOutputStream fos = openFileOutput("a.txt", MODE_PRIVATE); //得到输出流对象
fos.write(content.getBytes());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 读取文件内容
*/
public String readFiles(){
String content = null;
try {
//得到输入流
FileInputStream fis = openFileInput("a.txt"); //默认存放路径:/data/data/com.example.file/a.txt
//ByteArrayOutputStream类是在创建它的实例时,程序内部创建一个byte型数组的缓冲区,
//然后利用ByteArrayOutputStream的实例向数组中写入byte型数据。在网络传输中我们往往要
//传输很多变量,我们可以利用ByteArrayOutputStream把所有的变量收集到一起,然后一次性把数据发送出去。
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte [] buffer = new byte[1024]; //一次读取1024个字节
int len = 0;
//fis循环从a.txt文件中读取内容到缓存中,知道fis.read() 为-1时,表示写完
while((len = fis.read(buffer)) != -1){
//输出流调用write()方法,将指定buffer数组中从偏移量 off 开始的 len 个字节写入此输出流。
baos.write(buffer, 0, len);
}
//利用ByteArrayOutputStream把循环的变量值收集到一起,然后一次性把数据赋值给content变量。
content = baos.toString();
fis.close();
baos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return content;
}
}
运行结果: