IO流
来源:互联网 发布:网络监控能看到啥 编辑:程序博客网 时间:2024/06/08 03:30
一、IO用于在设备间进行数据传输的操作
二、分类
流向
输入流 读取数据
输出流 写出数据数据类型
字节流
字节输入流 InputStream
字节输出流 OutputStream字符流
字符输入流 Reader
字符输出流 Writer注意
1.除非文件用windows自带的记事本打开我们能够读懂,才采用字符流,否则建议使用字节流。
2.抽象类不能实例化,必须要找一个具体的子类
三、FileOutputStream写出数据
- 构造方法
1。File file = new File(“e:\demo\a.txt”);
2。File file = new File(“e:\demo”,”a.txt”);
3。File file = new File(“e:\demo”);
File file2 = new File(file,”a.txt”); - 操作步骤
1。创建字节输出流对象
2。调用write()方法
3。释放资源 - Demo
public class Demo { public static void main(String[] args) { // 为了在finally里面能够看到该对象就必须定义到外面,为了访问不出问题,还必须给初始化值 FileOutputStream fos = null; try { fos = new FileOutputStream("temp.txt"); fos.write("java".getBytes()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 如果fos不是null,才需要close() if (fos != null) { // 为了保证close()一定会执行,就放到这里了 try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } }}
public class FileInputStreamDemo { public static void main(String[] args) throws IOException { // FileInputStream(String name) // FileInputStream fis = new FileInputStream("fis.txt"); FileInputStream fis = new FileInputStream("FileOutputStreamDemo.java"); // // 调用read()方法读取数据,并把数据显示在控制台 // // 第一次读取 // int by = fis.read(); // System.out.println(by); // System.out.println((char) by); // // // 第二次读取 // by = fis.read(); // System.out.println(by); // System.out.println((char) by); // // // 第三次读取 // by = fis.read(); // System.out.println(by); // System.out.println((char) by); // // 我们发现代码的重复度很高,所以我们要用循环改进 // // 而用循环,最麻烦的事情是如何控制循环判断条件呢? // // 第四次读取 // by = fis.read(); // System.out.println(by); // // 第五次读取 // by = fis.read(); // System.out.println(by); // //通过测试,我们知道如果你读取的数据是-1,就说明已经读取到文件的末尾了 // 用循环改进 // int by = fis.read(); // while (by != -1) { // System.out.print((char) by); // by = fis.read(); // } // 最终版代码 int by = 0; // 读取,赋值,判断 while ((by = fis.read()) != -1) { System.out.print((char) by); } // 释放资源 fis.close(); }}
阅读全文
0 0
- 【IO流】IO框架
- IO流呀IO流
- 字符IO&数据流IO&对象流IO
- io流
- io流
- IO流
- IO流
- IO 流
- IO流
- io流
- IO流
- io流
- IO流
- IO流
- IO流
- IO流
- IO流
- IO流
- 网络层-8、ICMP
- Android知识点及资料汇总(不断更新中)
- Windows安装MongoDB
- 远程连接redis,并设置字符集
- 光标停止输入后触发事件
- IO流
- CListCtrl控件使用方法总结
- iPhone 8 到底值不值得买?
- Python3的迭代器
- JeeSite相关技术摘点(四)
- 苹果说,这次真的是By Design
- 从薛之谦事件看吃瓜群众
- 冒泡排序实现
- 什么情况下document.write会覆盖页面及覆盖原理解释