IO流概述:
IO流的分类
字节流写入数据:
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();}
}
字节流写入数据常用的三种方式:
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();}
}
字节流写入数据换行和追加写:
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();}
}
字节流写入数据异常处理:
正确关闭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());}}}}}