输入输出是站在当前程序的角度,输入即从外界读取数据,输入即向外界输出数据。写代码时要注意以下几点,见代码:
字节输入流:
- package TestFileInputStream;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.IOException;
- public class Test {
- public static void main(String[] args) {
- String name = "E:\day03\123.txt"; //读取地址
- FileInputStream f = null; //new一个字节输入流
- try {
- f = new FileInputStream(name);
- int len = 0;
- StringBuffer buffer = new StringBuffer();
- byte[] b = new byte[1024];
- //现代操作系统的内存管理都具有分页机制,而内存页的大小都是1024的整数倍
- //定义1024整数倍大小的缓冲区在分配内存时将不会形成碎片。
- while(-1 != (len = f.read(b))) { //.read没东西可读时会返回-1,当返回-1时停止循环
- String str = new String(b, 0, len);
- //每次都将读到byte[]里的内容传给str(String类型自带数组转字符串功能)
- buffer.append(str);//再将str拼接到StringBuffer类型变量里面
- }
- System.out.println(buffer.toString());
- } catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } finally {
- if(f != null) {
- try {
- f.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }
- }
字节输出流:
- package TestFileOutputStream;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- public class Test {
- public static void main(String[] args) {
- String str = "11111asdfsad5665asd12f";
- String path = "E:\day03\123.txt"; //输出路径要是绝对路径,即输出到哪个文件,不能只是目录
- FileOutputStream f = null; //字节输出流
- try {
- f = new FileOutputStream(path, true);
- byte[] bytes = str.getBytes(); //把要输出的字符串变成字节数组
- f.write(bytes); //字节流写入只能传字节
- f.flush();
- } catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } finally {
- if(f != null) { //判断f是否为空,若为空就说明没动过,不用关闭
- try {
- f.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }
- }