Java I/O 教程(三) FileOutputStream类

Java FileOutputStream 用于将字节数据写入文件。

如果你需要将原始数据写入文件,就使用FileOutputStream类。

Java.io.FileOutputStream class声明如下:

public class FileOutputStream extends OutputStream 

构造函数

FileOutputStream(File file)
Creates a file output stream to write to the file represented by the specified File object.

FileOutputStream(String name)
Creates a file output stream to write to the file with the specified name.

FileOutputStream(String name, boolean append)
Creates a file output stream to write to the file with the specified name.

常用函数

void write(byte[] ary)                        往文件输出流写指定字节数组
void write(byte[] ary, int off, int len)    往文件输出流写指定长度字节数组
void write(int b)                            往文件输出流写指定字节
void close()                                关闭文件输出流

例子1:

package com.dylan.io;

import java.io.FileOutputStream;

/**
 * @author xusucheng
 * @create 2017-12-31
 **/
public class FileOutputStreamWriteByte {
    public static void main(String[] args) {
        try {
            FileOutputStream fout = new FileOutputStream("D:\\testout.txt");
            fout.write(65);
            fout.close();
            System.out.println("success...");
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}


例子2:

package com.dylan.io;

import java.io.FileOutputStream;

/**
 * @author xusucheng
 * @create 2017-12-31
 **/
public class FileOutputStreamWriteString {
    public static void main(String[] args) {
        try {
            FileOutputStream fout = new FileOutputStream("D:\\testout.txt",true);
            String s = "Welcome to java.io.";
            byte b[] = s.getBytes(); //将字符串转为字节数组
            fout.write(b);
            fout.close();
            System.out.println("写入成功!");
        } catch (java.io.IOException e) {
            e.printStackTrace();
        }
    }
}


测试效果截图:


执行例子1:

执行例子2:




下一章:

Java I/O 教程(四) FileInputStream 类




  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值