[Java] 字节流与字符流的区别 →→→→→进入此内容的聊天室

来自 , 2020-01-19, 写在 Java, 查看 116 次.
URL http://www.code666.cn/view/81dc9bdb
  1. package fengke.byteandchar;
  2.  
  3. import java.io.File;
  4. import java.io.FileOutputStream;
  5. import java.io.OutputStream;
  6. /**
  7.  * 字節流
  8.  * @author 锋客
  9.  * 没有关闭字节流操作,但是文件中也依然存在了输出的内容,证明字节流是直接操作文件本身的
  10.  */
  11. public class ByteDemo {
  12.         public static void main(String[] args) throws Exception { // 异常抛出, 不处理
  13.                 // 第1步:使用File类找到一个文件
  14.                 File f = new File("e:" + File.separator + "test.txt"); // 声明File 对象
  15.                 // 第2步:通过子类实例化父类对象
  16.                 OutputStream out = null;
  17.                 // 准备好一个输出的对象
  18.                 out = new FileOutputStream(f);
  19.                 // 通过对象多态性进行实例化
  20.                 // 第3步:进行写操作
  21.                 String str = "鋒客測試";
  22.                 // 准备一个字符串
  23.                 byte b[] = str.getBytes();
  24.                 // 字符串转byte数组
  25.                 out.write(b);
  26.                 // 将内容输出
  27.                 // 第4步:关闭输出流
  28.                 // out.close();
  29.                 // 此时没有关闭 但任然可以看到文件中有Hello World!!!
  30.         }
  31.  
  32. }
  33.  
  34.  
  35. package fengke.byteandchar;
  36.  
  37. import java.io.File;
  38. import java.io.FileWriter;
  39. import java.io.Writer;
  40. /**
  41.  * 字符流
  42.  * @author 锋客
  43.  * 程序运行后会发现文件中没有任何内容,这是因为字符流操作时使用了缓冲区,而
  44.  * 在关闭字符流时会强制性地将缓冲区中的内容进行输出,但是如果程序没有关闭,则缓冲区中的内容是无法输出的,
  45.  */
  46. public class CharDemo {
  47.  
  48.         public static void main(String[] args) throws Exception { // 异常抛出, 不处理
  49.                 // 第1步:使用File类找到一个文件
  50.                 File f = new File("e:" + File.separator + "test1.txt");// 声明File 对象
  51.                 // 第2步:通过子类实例化父类对象
  52.                 Writer out = null;
  53.                 // 准备好一个输出的对象
  54.                 out = new FileWriter(f);
  55.                 // 通过对象多态性进行实例化
  56.                 // 第3步:进行写操作
  57.                 String str = "Hello World!!!";
  58.                 // 准备一个字符串
  59.                 out.write(str);
  60.                 // 将内容输出
  61.                 // 第4步:关闭输出流
  62.                 // out.close();
  63.                 // 此时没有关闭
  64.         }
  65.  
  66. }
  67.  
  68.  

回复 "字节流与字符流的区别"

这儿你可以回复上面这条便签

captcha