package cn.lianxi.test; import org.junit.Test; import java.io.*; import java.nio.charset.StandardCharsets; /** * 使用字节输出流写数据的步骤 * */ public class Demo { @Test public void test01() throws Exception { File file = new File("file1.txt"); //如果不存在 就创建 if(!file.exists()){ file.createNewFile(); } //创建in输入流 FileInputStream in = new FileInputStream(file); int i = -1; while ((i = in.read()) != -1){ System.out.println((char)i); } in.close(); } @Test public void test02() throws Exception { //创建out输出流 append参数: 默认不写是false,改为true可追加写入 FileOutputStream out = new FileOutputStream("file1.txt",true); //方式一 // out.write(97); // out.write(97); // out.write(97); //方式二 // byte[] bytes = {12,23,45,56,63}; // out.write(bytes); //方式三 byte[] bs1 = "abcdefg".getBytes(StandardCharsets.UTF_8); out.write(bs1,0,3);//从索引off开始,写length个字节 for (int i = 0; i < 5; i++) { out.write("hello".getBytes(StandardCharsets.UTF_8)); //换行的三种方式 out.write("\r\n".getBytes(StandardCharsets.UTF_8)); //out.write("\n".getBytes(StandardCharsets.UTF_8)); //out.write("\r".getBytes(StandardCharsets.UTF_8)); } out.close(); } @Test public void test03() throws Exception{ /** * 字节流写数据加异常处理 * 一般直接在外面包try{}catch{}, * 但是会有一个问题,如果写入数据失败会运行catch的内容, * 但是close方法没有运行到也就是资源没有被释放。所以在io操作一定要保存内存被释放。 * * 提供了finally块来执行所有清除操作 * finally:在异常处理时提供finally块来执行所有清除的操作。比如io流中的资源释放。 * 特点:被finally块控制的语句一定会执行,除非JVM退出 * */ //创建out输出流 FileOutputStream out = null; //append参数: 默认不写是false,改为true可追加写入 try { out = new FileOutputStream("file1.txt", true); //方式一 out.write(97); out.write(97); out.write(97); }catch (IOException e){ e.printStackTrace(); }finally { if(out!=null){ try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } } @Test public void test04() throws Exception { /** * 读取一个字节 * */ File file = new File("file2.txt"); //如果不存在 就创建 if(!file.exists()){ file.createNewFile(); } //创建字节输入流 FileInputStream in = new FileInputStream(file); //从这个输入流读取一个字节的数据。 int read = in.read(); System.out.println("read = " + read); in.close(); } @Test public void test05() throws Exception { /** * 循环读取该文件全部内容 * */ File file = new File("file3.txt"); //如果不存在 就创建 if(!file.exists()){ file.createNewFile(); } //创建字节输入流 FileInputStream in = new FileInputStream(file); //从这个输入流读取一个字节的数据。 int read = in.read(); //int read ; while(read != -1){ //while((read = in.read) != -1) System.out.println((char)read); read = in.read(); // } in.close(); } @Test public void test06() throws Exception { /** * 复制文本文件 * */ File file1 = new File("file2.txt"); if(!file1.exists()){ file1.createNewFile(); } File file2 = new File("file3.txt"); if(!file1.exists()){ file1.createNewFile(); } FileInputStream in = new FileInputStream(file1); FileOutputStream out = new FileOutputStream(file2); int bys; //实际写入的字节数 //设置一个 byte[] bytes = new byte[1024]; while((bys = in.read(bytes)) != -1){ out.write(bys); } out.close(); in.close(); } }