java之IO流(一)
生活随笔
收集整理的這篇文章主要介紹了
java之IO流(一)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前言
1:流
在Java IO中,流是一個核心的概念。流從概念上來說是一個連續的數據流。你既可以從流中讀取數據,也可以往流中寫數據。流與數據源或者數據流向的媒介相關聯。在Java IO中流既可以是字節流(以字節為單位進行讀寫),也可以是字符流(以字符為單位進行讀寫)。
2:IO最典型的數據源和目標媒介:
文件 管道 網絡連接 內存緩存 System.in, System.out, System.error(注:Java標準輸入、輸出、錯誤輸出)
從是讀媒介還是寫媒介的維度看,Java IO可以分為:
輸入流:InputStream和Reader
輸出流:OutputStream和Writer
而從其處理流的類型的維度上看,Java IO又可以分為:
字節流:InputStream和OutputStream
字符流:Reader和Writer
我們的程序需要通過InputStream或Reader從數據源讀取數據,然后用OutputStream或者Writer將數據寫入到目標媒介中。其中,InputStream和Reader與數據源相關聯,OutputStream和writer與目標媒介相關聯。 以下的圖說明了這一點:
3:Java IO的基本用法
字節流寫文件
public static void writeByteToFile() throws IOException{String hello= new String( "hello word!");byte[] byteArray= hello.getBytes();File file= new File( "d:/test.txt");//因為是用字節流來寫媒介,所以對應的是OutputStream //又因為媒介對象是文件,所以用到子類是FileOutputStreamOutputStream os= new FileOutputStream( file);os.write( byteArray);os.close();}字節流讀文件
public static void readByteFromFile() throws IOException{File file= new File( "d:/test.txt");byte[] byteArray= new byte[( int) file.length()];//因為是用字節流來讀媒介,所以對應的是InputStream//又因為媒介對象是文件,所以用到子類是FileInputStreamInputStream is= new FileInputStream( file);int size= is.read( byteArray);System. out.println( "大小:"+size +";內容:" +new String(byteArray));is.close();}字符流讀文件
public static void writeCharToFile() throws IOException{String hello= new String( "hello word!");File file= new File( "d:/test.txt");//因為是用字符流來讀媒介,所以對應的是Writer,又因為媒介對象是文件,所以用到子類是FileWriterWriter os= new FileWriter( file);os.write( hello);os.close();}字符流寫文件
public static void readCharFromFile() throws IOException{File file= new File( "d:/test.txt");//因為是用字符流來讀媒介,所以對應的是Reader//又因為媒介對象是文件,所以用到子類是FileReaderReader reader= new FileReader( file);char [] byteArray= new char[( int) file.length()];int size= reader.read( byteArray);System. out.println( "大小:"+size +";內容:" +new String(byteArray));reader.close();}字節流轉換為字符流
--------------------------------------------------------------- 注:我這有個學習Python基地,里面有很多學習資料,感興趣的+Q群:895817687 ---------------------------------------------------------------public static void convertByteToChar() throws IOException{File file= new File( "d:/test.txt");//獲得一個字節流InputStream is= new FileInputStream( file);//把字節流轉換為字符流,其實就是把字符流和字節流組合的結果。Reader reader= new InputStreamReader( is);char [] byteArray= new char[( int) file.length()];int size= reader.read( byteArray);System. out.println( "大小:"+size +";內容:" +new String(byteArray));is.close();reader.close();}未完待續
總結
以上是生活随笔為你收集整理的java之IO流(一)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java -jar 和 java -cp
- 下一篇: 史上最全 Python Re 模块讲解(