/** * * 在Java IO中,流是一個核心的概念。 * 流從概念上來講是一個連續的數據流。 * 既能夠從流中讀取數據,也能夠往流中寫數據。 * 流與數據源或者數據流向的媒介相關聯。 * 在Java IO中流既能夠是字節流(以字節爲單位進行讀寫),也能夠是字符流(以字符爲單位進行讀寫)。 */ public class JavaIoTest { /** * 字節流對應的類應該是InputStream和OutputStream * * @throws IOException */ public static void writeByteToFile() throws IOException { String hello = "hello world"; byte[] bytes = hello.getBytes(); File file = new File("/Users/grug/test.txt"); //字節流寫,用outPutStream,寫文件用FileOutPutStream OutputStream os = new FileOutputStream(file); os.write(bytes); os.close(); } public static void readByteFromFile() throws IOException { File file = new File("/Users/grug/test.txt"); byte[] fileByte = new byte[(int) file.length()]; InputStream inputStream = new FileInputStream(file); //buffer 能夠提升讀取速度,比inputStream 一個一個字節讀要快 BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream, 2 * 1024); // inputStream.read(fileByte); bufferedInputStream.read(fileByte); System.out.println(new String(fileByte)); inputStream.close(); } /** * 字符流對應的類應該是Reader和Writer * * @throws IOException */ public static void writeCharToFile() throws IOException { String hello = "hello world"; File file = new File("/Users/grug/writeCharToFile_test.txt"); //字符流寫文件 Writer fileWrite = new FileWriter(file); fileWrite.write(hello); fileWrite.close(); } public static void readCharFromFile() throws IOException { File file = new File("/Users/grug/writeCharToFile_test.txt"); Reader reader = new FileReader(file); //用buffer提升讀取速度,能夠指定每次讀取的大小 BufferedReader bufferedReader = new BufferedReader(reader, 2 * 1024); char[] chars = new char[(int) file.length()]; bufferedReader.read(chars); String result = new String(chars); System.out.println(result); } /** * 管道主要用來實現同一個虛擬機中的兩個線程進行交流 * * @throws IOException */ public static void pipedStream() throws IOException { final PipedOutputStream pipedOutputStream = new PipedOutputStream(); final PipedInputStream pipedInputStream = new PipedInputStream(pipedOutputStream); Thread thread1 = new Thread(new Runnable() { @Override public void run() { try { pipedOutputStream.write("hello pipe".getBytes()); } catch (IOException e) { e.printStackTrace(); } } }); Thread thread2 = new Thread(() -> { try { byte[] dataByte = new byte[10]; pipedInputStream.read(dataByte); System.out.println(new String(dataByte)); } catch (IOException ex) { try { pipedInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } }); thread1.start(); thread2.start(); } /** * 字節流能夠轉換成字符流, * * @throws IOException */ public static void convertBytesToChars() throws IOException { File file = new File("/Users/grug/test.txt"); InputStream inputStream = new FileInputStream(file); Reader fileRead = new InputStreamReader(inputStream); char[] chars = new char[(int) file.length()]; fileRead.read(chars); String result = new String(chars); System.out.println(result); } public static void main(String[] args) { try { pipedStream(); } catch (IOException ex) { ex.printStackTrace(); } } }