JAVAIO-FileOutputStream

java.io.FileOutputStream是java.io.OutputStream的具体实现,提供连接到文件的输出流。

public class FileOutputStream extends OutputStream

类中实现了OutputStream的所有常用方法

public native void write(int b) throws IOException
public void write(byte[] data) throws IOException
public void write(byte[] data, int offset, int length) throws IOException
public native void close() throws IOException

跟之前的FileInputStream相同,FileOutputStream的四个方法也都是实际上的native方法。如下的三种构造器,区别在于文件是如何指定的:

public FileOutputStream(String filename) throws IOException
public FileOutputStream(File file) throws IOException
public FileOutputStream(FileDescriptor fd)

和FileInputStream不同的是,如果指定的文件不存在,那么FileOutputStream会创建它,如果文件存在,FileOutputStream会覆盖它。这个特性让我们使用的时候有些不太方便,有的时候,往往我们需要往一个文件里面添加一些数据,比如向日志文件里面存储记录。这时候,第四个构造函数就体现了它的作用

  public FileOutputStream(String name, boolean append) throws IOException

如果append设置为true,那么如果文件存在,FileOutputStream会向文件的末尾追加数据,而不是覆盖。
下面的程序获取两个文件名作为参数,然后把第一个文件复制到第二个文件:

public class FileCopier {
  public static void main(String[] args) {
    if(args!=2) {
      System.err.println("error input");//输入异常。
      return;
    }
    try {
      copy(args[0],args[1]);//调用复制文件的方法
    } catch (IOException e) {System.err.println(e);}
  }
  public static void copy (String inFile, String outFile) throws IOException {
    FileInputStream fin = null;
    FileOutputStream fout = null;
    try{
      fin = new FileInputStream(inFile);
      fout = new FileOutputStream(outFile);
      StreamCopier.copy(fin,fout);
    }
    finally {
      try {
        if (fin != null) fin.close();
      } catch (IOException e) {}
      try {
        if (fout != null) fout.close();
      } catch (IOException e) {}
  }
}
public class StreamCopier {
  public static void copy(InputStream in,OutputStream out) throws IOException {
    //Do not allow other threads read from the input or write the output
    synchronized (in) {
      synchronized (out) {
        byte[] buffer = new byte[256];
        while(true) {
          int bytesRead = in.read(buffer);
          if(bytesRead == -1) break;
          out.write(buffer,0,bytesRead);
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、流的概念和作用。 流是一种有顺序的,有起点和终点的字节集合,是对数据传输的总成或抽象。即数据在两设备之间的传输...
    布鲁斯不吐丝阅读 10,118评论 2 95
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,786评论 18 399
  • IO简单概述 IO解决问题 : 解决设备与设备之间的数据传输问题(硬盘 -> 内存 内存 -> 硬盘) 读和写文...
    奋斗的老王阅读 3,474评论 0 53
  • (一)Java部分 1、列举出JAVA中6个比较常用的包【天威诚信面试题】 【参考答案】 java.lang;ja...
    独云阅读 7,146评论 0 62
  • 我很想知道一只猫的心理活动 咬纸箱子牙齿痒痒的时候,在想要把这个玩意儿干掉吗 蹲在猫砂里拉粑粑的时候,会不会因为那...
    三饭姨阅读 379评论 0 0