java基础 IO

1. IO流概述:

2.IO流的分类

3.字节流写入数据:

package wwx;

import jdk.swing.interop.SwingInterOpUtils;

import java.io.*;

public class Test {
    public static void main(String[] args) throws IOException {
       //指定写入文件的路径 需要抛出异常
        FileOutputStream fileOutputStream = new FileOutputStream("E:\\wwx\\xx\\w.txt");
        // 写入数据到磁盘中
        fileOutputStream.write(98);
        //关闭字节输出流
        fileOutputStream.close();
    }
}


4.字节流写入数据常用的三种方式:

package wwx;

import jdk.swing.interop.SwingInterOpUtils;

import java.io.*;

public class Test {
    public static void main(String[] args) throws IOException {
        //指定写入文件的路径 需要抛出异常
        FileOutputStream fileOutputStream = new FileOutputStream("E:\\wwx\\xx\\w.txt");
        // 写入数据到磁盘中
        // fileOutputStream.write(98);

        byte[] bytes = {98, 99, 100, 101};
        fileOutputStream.write(bytes);

        //关闭字节输出流
        fileOutputStream.close();

        FileOutputStream fileOutputStream1 = new FileOutputStream("E:\\wwx\\xx\\wx.txt");
        fileOutputStream1.write(97);
        fileOutputStream1.close();

    }
}


5.字节流写入数据换行和追加写:

package wwx;

import jdk.swing.interop.SwingInterOpUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;

public class Test {
    public static void main(String[] args) throws IOException {

        FileOutputStream fileOutputStream = new FileOutputStream("wwx.txt");//+ ,输入ture,可改成追加模式



        for (int i = 0; i < 3 ; i++) {
            fileOutputStream.write("wwx".getBytes());
            fileOutputStream.write("\n".getBytes());
            fileOutputStream.write("222".getBytes());
            fileOutputStream.write("\n".getBytes());
        }

        fileOutputStream.close();
    }
}


 

 6.字节流写入数据异常处理:

6.1正确关闭IO资源: 

package wwx;

import jdk.swing.interop.SwingInterOpUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;

public class Test {
    public static void main(String[] args) {
        FileOutputStream f=null;
        try{
           f = new FileOutputStream("wwx.txt");
        //若该路径有错误,则f为null,f.cloes()即为空指针异常,会被catch捕获空指针异常

            f.write("我的世界".getBytes());
            int j=1/0;//算数异常,0不能为分母

        }catch (IOException e){
            System.out.println(e.getStackTrace());
        }finally {
          if(f!=null){
              try{
                  f.close();//此时f.close()在finally()中一定会执行,资源就会关闭
                  System.out.println("关闭IO资源成功...");
              }catch(IOException e){
                  System.out.println(e.getStackTrace());
              }
          }
        }
    }

}


 

7.IO框架:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值