package com.itheima.stream; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.io.*; @SpringBootTest @RunWith(SpringJUnit4ClassRunner.class) public class FileTest { /** * 使用字節緩衝流流出 * @throws IOException */ @Test public void test06() throws IOException { FileOutputStream stream = new FileOutputStream("C:/Users/Administrator/Desktop/遠程辦公/aaa.txt"); // 建立 BufferedOutputStream BufferedOutputStream outputStream = new BufferedOutputStream(stream); String out="BufferedOutputStream outputStream"; outputStream.write(out.getBytes()); outputStream.flush(); outputStream.close(); } /** * 使用字節緩衝流讀取 * @throws IOException */ @Test public void test05() throws IOException { FileInputStream stream = new FileInputStream("C:/Users/Administrator/Desktop/遠程辦公/aaa.txt"); // 建立 BufferedInputStream BufferedInputStream inputStream = new BufferedInputStream(stream); // 2.讀取 int data=0; while ((data=inputStream.read())!=-1){ System.out.println((char) data); } } /** * 演示FileOutputStream FileInputStream 實現文件的複製 * @throws IOException */ @Test public void test04() throws IOException { FileInputStream stream = new FileInputStream("C:/Users/Administrator/Desktop/遠程辦公/aaa.txt"); FileOutputStream outStream = new FileOutputStream("C:/Users/Administrator/Desktop/遠程辦公/aaabbb.txt",false); byte[] bytes=new byte[3]; int data=0; while((data=stream.read(bytes))!=-1){ outStream.write(bytes,0,data); } stream.close(); outStream.close(); } /** * 演示FileOutputStream 文件字節輸出流 * @throws IOException */ @Test public void test03() throws IOException { FileOutputStream stream = new FileOutputStream("C:/Users/Administrator/Desktop/遠程辦公/aaabbb.txt",true); String out ="歡樂中國年"; stream.write(out.getBytes()); stream.close(); } /** * 演示FileOutputStream 文件字節輸出流 * @throws IOException */ @Test public void test02() throws IOException { FileOutputStream stream = new FileOutputStream("C:/Users/Administrator/Desktop/遠程辦公/aaabbb.txt"); stream.write(97); stream.close(); } @Test public void test01() throws IOException { //文件字節輸入流 FileInputStream stream = new FileInputStream("C:/Users/Administrator/Desktop/遠程辦公/aaa.txt"); byte[] bytes= new byte[2]; int data=0; while((data=stream.read(bytes))!=-1){ // stream.read() 讀取出來的是它的編碼,能夠轉化爲字符 char System.out.println(new String(bytes,0,data)); } stream.close(); } /** * 流的分類 * 按方向 [重點] * 輸入流: 將<存儲設備>中的內容讀取到內存中 * 硬盤 ---->>>>> 內存 input * * 內存 --->>>存儲設備 output * */ @Test public void test() throws IOException { //文件字節輸入流 FileInputStream stream = new FileInputStream("C:/Users/Administrator/Desktop/遠程辦公/aaa.txt"); while(stream.read()!=-1){ // stream.read() 讀取出來的是它的編碼,能夠轉化爲字符 char System.out.println((char) stream.read()); } stream.close(); } }