java的IO流
顾名思义IO就是input和output
程序运行后的数据都在内存中,所有当程序中的数据和外部的数据进行交互时就会用到IO流操作,下面介绍具体用法:
1、input
input输入流就是其他地方的数据读入内存中,具体方法如下:
File file =new File("d:/test.java");//定义文件 //file.createNewFile();//创建文件 //file.delete();//删除文件 //file.length();//获取文件内容的字节长度 //file.exists();//判断文件是否存在 //字节为单位 InputStream is=new FileInputStream(file);//字节流,InoutStream是抽象类不能被实例化,通过FileInputStream来实例化 byte[] arr =new byte[10];//以10个字节为单位读入,注意utf-8中一个中文3个字符gbk中一个中文两个字符,如果切割中文会乱码 //字符为单位 InputStreamReader isr=new InputStreamReader(is);//转字符流不会有中文乱码 //字符串对象为单位,可以用readline函数按行读取 BufferedReader bis=new BufferedReader(isr);//以字符串为单位读取 Reader reader=new FileReader(file);//字符流//如果是json对象的话 ObjectInputStream ois=new ObjectInputStream(is); List<Student> list=(List<Student>)ois.readObject();//强转 System.out.println(list); ois.close(); //测试字节字符流 int i=isr.read(); while(i!=-1){ System.out.print((char)i); i=isr.read(); } bis.close(); isr.close(); is.close();//后定义的先关闭
2、output输出流
File file =new File("d:/test.java"); OutputStream os=new FileOutputStream(file,false); os.write("112233".getBytes());//输出内容 os.flush();//输出要刷新一下,这就成功了,记得关闭输出流对象 //如果是Object类型的要注意,输出的Object一定要实现Serializable接口,也就是二进制输出,虽然输出看不懂,但是读入后我们是可以用的 StudentService studentService=new StudentServiceImpl(); List<Student> list=studentService.queryAll();//获取一个list对象 ObjectOutputStream oos=new ObjectOutputStream(os);//转化为Object输出流 oos.writeObject(list); oos.close(); os.close();
浙公网安备 33010602011771号