• 00089_字节输出流OutputStream


    1、字节输出流OutputStream

      (1)OutputStream此抽象类,是表示输出字节流的所有类的超类。操作的数据都是字节,定义了输出字节流的基本共性功能方法;
      (2)输出流中定义都是写write方法。

    2、FileOutputStream类

      (1)OutputStream有很多子类,其中子类FileOutputStream可用来写入数据到文件;

      (2)FileOutputStream类,即文件输出流,是用于将数据写入 File的输出流。

     1 import java.io.File;
     2 import java.io.FileOutputStream;
     3 import java.io.IOException;
     4 
     5 public class FileOutputStreamDemo {
     6     public static void main(String[] args) throws IOException {
     7         // 需求:将数据写入到文件中。
     8         // 创建存储数据的文件。
     9         File file = new File("d:\HelloWorld.txt");
    10         // 创建一个用于操作文件的字节输出流对象。一创建就必须明确数据存储目的地。
    11         // 输出流目的是文件,会自动创建。如果文件存在,则覆盖。
    12         FileOutputStream fos = new FileOutputStream(file);
    13         // 调用父类中的write方法。
    14         byte[] data = "I love Java!".getBytes();
    15         fos.write(data);
    16         // 关闭流资源。
    17         fos.close();
    18     }
    19 }

    3、给文件中续写和换行

      (1)在FileOutputStream的构造函数中,可以接受一个boolean类型的值,如果值true,就会在文件末位继续添加;

      (2)代码演示:

     1 import java.io.File;
     2 import java.io.FileOutputStream;
     3 
     4 public class FileOutputStreamDemo2 {
     5     public static void main(String[] args) throws Exception {
     6         File file = new File("d:\HelloWorld.txt");
     7         FileOutputStream fos = new FileOutputStream(file, true);
     8         String str = "
    " + "and you?";
     9         fos.write(str.getBytes());
    10         fos.close();
    11     }
    12 }

    4、IO异常的处理

     1 import java.io.File;
     2 import java.io.FileOutputStream;
     3 import java.io.IOException;
     4 
     5 public class FileOutputStreamDemo3 {
     6     public static void main(String[] args) {
     7         File file = new File("d:\HelloWorld.txt");
     8         // 定义FileOutputStream的引用
     9         FileOutputStream fos = null;
    10         try {
    11             // 创建FileOutputStream对象
    12             fos = new FileOutputStream(file);
    13             // 写出数据
    14             fos.write("abcde".getBytes());
    15         } catch (IOException e) {
    16             System.out.println(e.toString() + "----");
    17         } finally {
    18             // 一定要判断fos是否为null,只有不为null时,才可以关闭资源
    19             if (fos != null) {
    20                 try {
    21                     fos.close();
    22                 } catch (IOException e) {
    23                     throw new RuntimeException("");
    24                 }
    25             }
    26         }
    27     }
    28 }
  • 相关阅读:
    cogs 896. 圈奶牛
    bzoj 1670: [Usaco2006 Oct]Building the Moat护城河的挖掘
    bzoj 1007: [HNOI2008]水平可见直线
    bzoj 3673: 可持久化并查集 by zky
    bzoj 3545: [ONTAK2010]Peaks
    bzoj 1901: Zju2112 Dynamic Rankings
    动态 K th
    poj 2104 K-th Number
    bzoj 3657 斐波那契数列(fib.cpp/pas/c/in/out)
    青蛙的约会
  • 原文地址:https://www.cnblogs.com/gzdlh/p/8097254.html
Copyright © 2020-2023  润新知