Java FileOutputStream类

定义

public FileOutputStream(String name)
public FileOutputStream(File file)
public FileOutputStream(File file,boolean append)
public FileOutputStream(FileDescriptor fdObj)

参数

file:要打开以进行写入的文件。append:是否往文件中添加数据。

异常

FileNotFoundException:无法创建或者操作文件

SecurityException:无权限操作此文件

方法

//将指定的字节写入管道输出流。
public void write(int b)
public void write(byte[] b,int off,int len)

将指定的字节写入此字节数组输出流,此方法继承于OutputStream,可以参考OutputStream.write

//返回与此文件输出流关联的唯一FileChannel对象。
public FileChannel getChannel()
//返回与此流关联的文件描述符。
public final FileDescriptor getFD()
//关闭输出流
public void close()

例子

public static void main(String[] args)
{
    OutputStream fs = null;
    try
    {
        StringBuffer buf = new StringBuffer();
        buf.append("Hello JAVASCHOOL!").append("\r\n");
        buf.append("Hello www.51gjie.com").append("\r\n");
        fs = new FileOutputStream(new File("c:\\51gjie.txt"), true)
        fs.write(buf.toString().getBytes())
    }
    catch(Exception e)
    {}
    finally
    {
        fs.close();
    }
}

1. FileOutputStream是文件字节输出流,它把内存中的数据写入到硬盘的文件中,一般用于向文件进行写入操作。

2. FileOutputStream默认会覆盖原文件数据,如果要在文件后面添加数据,append一定要设置成true。

3. 使用完流之后,要进行关闭,否侧会占用JVM的一定资源。