IO编程之-演示FileOutputStream类的用法

本文演示了如何使用Java的FileOutputStream类将内存中的数据写入到文件中,包括通过键盘录入内容并将其转换为字节数组进行写入。

/**
 * 2018.11.4
 * 作者:孟小鱼
 * 内容:演示FileOutputStream类的用法(将内存里的内容读取到一个文件中)
 * (内存当中的的内容可以通过键盘录入)
 */
package com.io2;
import java.io.*;
import java.util.Scanner;

public class iotest {
    public static void main(String[] args) {
        /*
         * 如果e:\\bb.txt不存在,那么操作会自动创建出一个文件
         * 如果不存在就危险了,可能会将原来的文件覆盖
         */
        File f=new File("e:\\bb.txt");
        //字节输出流
        FileOutputStream fos=null;
        
        try {
        //因为File没有读写操作,所以要借助OutputStream    
        fos=new FileOutputStream(f);
        /*
        String s="孟小鱼想要去北航\r\n";
        String s1="那他必须加油";
        
        fos.write(s.getBytes());
        fos.write(s1.getBytes());
        */

        //定义一个字节数组,相当于缓冲
        byte []bytes=new byte[1024];
        
        Scanner sc=new Scanner(System.in);
        String s=sc.next();
        //如何将String只能换成bytes数组
        
        byte []bytes1=s.getBytes();
        fos.write(s.getBytes());
        
        } catch (Exception e) {
            e.printStackTrace();
        }finally
        {
            try {
                //关闭文件
                fos.close();
            } catch (Exception e2) {
                e2.printStackTrace();
            }

        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值