字符流
来源:互联网 发布:utf8编码转换器c语言 编辑:程序博客网 时间:2024/06/04 23:40
1. 字符流
在程序中一个字符等于两个字节,Java为我们提供了Reader和Writer两个专门操作字符流的类
1) 字符输出流:Writer
Writer是一个字符流,它是一个抽象类,所以要使用它,也必须通过其子类来实例化它后才能使用它。
Writer类的常用方法方法名称 描述 public abstract void close() throws IOException 关闭输出流 public void write(String str) throws IOException 将字符串输出 public void write(char cbuf) throws IOException 将字符数组输出 public abstract void flush() throws IOException 强制性清空缓存
向一个文本文件中通过字符输出流写入数据
public static void main(String[] args) throws Exception { // 声明一个File对象 File file = new File("hellowolrd.txt"); // 声明一个Write对象 Writer writer = null; // 通过FileWriter类来实例化Writer类的对象并以追加的形式写入 writer = new FileWriter(file, true); // 声明一个要写入的字符串 String str = "字符串形式写入Helloworld"; // 写入文本文件中 writer.write(str); // 刷新 writer.flush(); // 关闭字符输出流 writer.close(); }
2) 字符输入流:Reader
Reader本身也是一个抽象类,同样,如果使用它,我们需要通过其子类来实例化它才可以使用它。
Reader类的常用方法方法名称 描述 public abstract void close() throws IOException public int read() throws IOException public int read(char cbuf) throws IOException
在上面的基础上把文本中的内容读出来,并且显示在控制台上
public static void main(String[] args) throws Exception { // 声明一个File对象 File file = new File("hellowolrd.txt"); // 声明一个Reader类的对象 Reader reader = null; // 通过FileReader子类来实例化Reader对象 reader = new FileReader(file); // 声明一个字符数组 char[] c = new char[1024];// // 将内容输出// int len = reader.read(c); //循环方式一个一个读 int len=0; int temp=0; while((temp=reader.read())!=-1){ c[len]=(char)temp; len++; } // 关闭输入流 reader.close(); // 把char数组转换成字符串输出 System.out.println(new String(c, 0, len)); }
2. 字符流与字节流的区别
操作字节流操作时本身不会用到缓冲区,是文件本身直接操作,而字节流在操作时就使用到了缓冲区。
如果我们在操作字符流的时候,不关闭流,我们写入的数据是无法保存的。所以在操作字符流的时候一定要记得关闭流。
- 字符流
- 字符流
- 字符流
- 字符流
- 字符流
- 字符流
- 字符流
- 字符流
- 字符流
- 字符流
- 字符流
- 字符流
- 字符流
- 字符流
- 字符流
- 字符流
- 字符流
- 字符流
- 解决Android中解析xml时遇到的MalformedURLException异常
- View.VISIBLE、INVISIBLE、GONE的区别
- sqlserver在企业管理器中设置datetime默认值为当前时间
- Bionic C 库概述(Bionic Overview)
- log4cxx编译、使用
- 字符流
- nutch-1.2和nutch-1.3的配置使用
- 使用spring.net+nibernate时如何用aspnet_regiis加密数据库连接字符串
- JNI中Java与C++的类型转换与相互调用
- ceshi2
- HBase性能优化方法总结
- 将十进制整形数转换成二进制,然后通过字符型输出 自己实现的一个简单的例子
- [Android]attrs.xml文件中属性类型format值的格式
- [acm] 动态规划相关的题目 [ 个人 ]