Java中的IO技术使用总结
生活随笔
收集整理的這篇文章主要介紹了
Java中的IO技术使用总结
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
請尊重他人勞動成果,請勿隨意剽竊,轉載請注明,謝謝!轉載請注明出處:http://blog.csdn.net/evan_man/article/details/51983126
? ?? ? ? Java中對于IO操作擁有的類有很多,很容易記混淆,需要讀者認真梳理,這樣才能使用的順手,不至于出太大的錯誤。本篇博客將對Java中涉及到的所有IO操作,做一次總結,幫助各位去梳理一下看似混亂的IO操作方法。此外,如果之前閱讀過博客《OkHttp深入學習(四)——0kio》http://blog.csdn.net/evan_man/article/details/51204469,可以跟本篇博客進行對比,了解okio的優勢所在。 Java中的IO操作大體分為如下四類:- InputStream :
- 該類用于讀取字節流數據,往下大體又分為如下四類:
- FileInputStream、ObjectInputStream、FilterInputStream(BufferedInputStream)
- OutputStream :
- 該類用于寫入字節流數據,往下大體又分為如下四類:
- FileOutputStream、ObjectOutputStream、FilterOutputStream(BufferedOutputStream)?
- Reader
- 該類用于讀取字符流數據,往下大體又分為如下兩類:
- InputStreamReader(FileReader)、BufferedReader
- Writer
- 該類用于寫入字符流數據,往下大體又分為如下三類:
- OutputStreamWriter(FileWriter)、BufferedWriter、PrintWriter?
PartA 讀寫字節(最原始)
InputStream
繼承關系: public?abstract class?InputStream ?extends Object ?implements?Closeable 是一個抽象類,聲明了一個read()抽象方法,該方法讀取一個字節并返回讀取到的字節值;同時該方法會發生阻塞行為,知道有字節流可讀則返回;包含方法: abstract?int read(); 該方法返回一個0到255的比特值,如果沒有比特數據可以讀取返回-1;該方法會造成線程阻塞。 int available(); int read(byte[] b); int read(byte[] b, int off, int len); void close(); 著名的子類:
- FileInputStream
- 繼承關系:public class FileInputStream ?extends InputStream
- 構造器:constructors:
- FileInputStream(File file);根據File對象打開一個文件的輸入連接
- FileInputStream(String name);根據文件路徑打開一個對應文件的輸入連接
- 功能
- 用于對文件內容進行二進制讀取,如視頻、圖片、聲音等文本內容
- ObjectInputStream
- 繼承關系:public class ObjectInputStream ?extends InputStream?implements ObjectInput, ObjectStreamConstants
- 構造器:constructors:
- ObjectInputStream(InputStream in);從一個特定的InputStream流中創建一個ObjectInputStream對象
- 功能
- 通過readObject方法反序列化出InputStream對應的對象
- readObject() ;Read an object from the ObjectInputStream.
- readxx(); 讀取基本數據類型,如readInt();
- BufferedInputStream
- 繼承關系:public class BufferedInputStream ?extends FilterInputStream
- 構造器:constructors:
- BufferedInputStream(InputStream in) ;使用默認緩存大小
- BufferedInputStream(InputStream in, int size) ;使用特定緩存大小
- 功能
- 減少IO訪問次數,一次讀取多個字節的數據
OutputStream
繼承關系:public?abstract class?OutputStream ?extends Object?implements?Closeable, Flushable 是一個抽象類,聲明了一個write(int)抽象方法,該方法向輸出流中寫入一個字節的數據;
包含方法: abstract?void write(int b); 寫入一個比特輸入到輸出流中,對于參數b的高24位自動忽略。 void write(byte[] b) Writes b.length bytes from the specified byte array to this output stream. void write(byte[] b, int off, int len) Writes len bytes from the specified byte array starting at offset off to this output stream. void flush() Flushes this output stream and forces any buffered output bytes to be written out. void close() Closes this output stream and releases any system resources associated with this stream. ? ?? 著名的子類:
- FileOutputStream
- 繼承關系:public class FileOutputStream ?extends OutputStream
- 構造器:constructors:
- FileOutputStream(File file);
- FileOutputStream(File file, boolean append) ;
- 根據一個File對象,創建一個FileOutputStream流,第二個參數為true表示寫入的其實位置位于文本的末尾。否則從文本的起始位置寫入新信息。
- FileOutputStream(String name) ;
- FileOutputStream(String name, boolean append)
- 根據一個FilePath地址,創建一個FileOutputStream流,第二個參數為true表示寫入的其實位置位于文本的末尾。否則從文本的起始位置寫入新信息。
- 功能
- 對文本的二進制原始數據的寫入
- ObjectOutputStream
- 繼承關系:public class ObjectOutputStream ?extends OutputStream?implements ObjectOutput, ObjectStreamConstants
- 構造器:constructors:
- ObjectOutputStream(OutputStream out) ;Creates an ObjectOutputStream that writes to the specified?OutputStream.
- 功能
- 通過writeObject方法序列化對象到ObjectOutputStream綁定的輸出流中
- void writeObject(Object obj) ;Write the specified object to the ObjectOutputStream.
- writexx(); 讀取基本數據類型,如writeInt();
- BufferedOutputStream
- 繼承關系:public class BufferedOutputStream ?extends?FilterOutputStream
- 構造器:constructors:
- BufferedOutputStream(OutputStream out) ;使用默認緩存大小
- BufferedOutputStream(OutputStream out, int size) ;使用指定緩存大小
- 功能
- 減少IO訪問次數,一次寫入多個字節的數據
PartB ?讀寫字符(Unicode文本)(多個字節流一起讀)
Reader
繼承關系:public?abstract class?Reader ?extends Object?implements?Readable, Closeable 是一個抽象類,聲明了一個 read(char[] cbuf, int off, int len) 抽象方法,從流中讀取字符到數組中; 包含方法: int read() 讀取一個單字符 abstract int read(char[] cbuf, int off, int len) Reads characters into a portion of an array. abstract void close() Closes the stream and releases any system resources associated with it. 著名的子類:
Direct Known Subclasses
- InputStreamReader
- 繼承關系:public class InputStreamReader ?extends Reader
- 構造器:constructors:
- InputStreamReader(InputStream in) ;創建一個InputStreamReader使用默認的字符集.
- InputStreamReader(InputStream in, Charset cs) ;
- InputStreamReader(InputStream in, CharsetDecoder dec) ;
- InputStreamReader(InputStream in, String charsetName) ;
- 創建一個InputStreamReader使用特定的字符集
- 功能
- 是比特流到字符流之前的橋梁,讀取字符流數據然后解碼成對應的字符
- BufferedReader
- 繼承關系:public class BufferedReader ?extends Reader
- 構造器:constructors:
- BufferedReader(Reader in) ;Creates a buffering character-input stream that uses a?default-sized?input buffer.
- BufferedReader(Reader in, int sz) ;Creates a buffering character-input stream that uses an input buffer of?the specified size.
- 功能
- 提供了一個緩存的功能
- FileReader(使用默認的編解碼,使用默認大小的緩存,故應該不建議使用)
- 繼承關系:public class FileReader ?extends?InputStreamReader
- 構造器:constructors:
- FileReader(File file) ;Creates a new FileReader, given the File to read from.
- FileReader(String fileName) ;Creates a new FileReader, given the name of the file to read from.
- 功能
- 方便與對文件中的字節流數據進行字符方式讀取,使用默認的字符集和默認的緩存大小。
- 方便與對文件中的字節流數據進行字符方式讀取,使用默認的字符集和默認的緩存大小。
Writer
繼承關系:public?abstract class?Writer ?extends Object?implements?Appendable, Closeable, Flushable 是一個抽象類,聲明了一個 write(char[] cbuf, int off, int len)抽象方法,向流中寫入部分字符;
包含方法: void write(int c) ? ? 寫入一個單字符 abstract void write(char[] cbuf, int off, int len) Writes a portion of an array of characters. Writer append(char c) Appends the specified character to this writer. Writer append(CharSequence?csq) Appends the specified character sequence to this writer. Writer append(CharSequence?csq, int start, int end) Appends a subsequence of the specified character sequence to this writer. abstract void close() Closes the stream, flushing it first. abstract void flush() Flushes the stream. 著名的子類:
- ?OutputStreamWriter
- 繼承關系:public class OutputStreamWriter ?extends Writer
- 構造器:constructors:
- OutputStreamWriter(OutputStream out) ;創建一個OutputStreamWriter使用默認的字符集.
- OutputStreamWriter(OutputStream out, Charset cs) ;
- OutputStreamWriter(OutputStream out, CharsetEncoder enc) ;
- OutputStreamWriter(OutputStream out, String charsetName) ;
- 創建一個OutputStreamWriter使用特定的字符集
- 功能
- 是比特流到字符流之前的橋梁,對字符進行編碼然后以二進制格式存入輸出流中
- BufferedWriter
- 繼承關系:public class BufferedWriter ?extends Writer
- 構造器:constructors:
- BufferedWriter(Writer out) ;Creates a buffered character-output stream that uses a?default-sized?output buffer.?
- BufferedWriter(Writer out, int sz) ;Creates a new buffered character-output stream that uses an output buffer of?the given size.
- 功能
- 提供了一個緩存的功能
- PrintWriter(用于以文本格式打印字符串和數字的方法,就是我們習慣的println、printf等)
- 繼承關系:public class PrintWriter ?extends Writer
- 構造器:constructors:(支持了所有的類型,構造該對象)
- PrintWriter(File file) ;Creates a new PrintWriter, without automatic line flushing, with the specified file.?
- PrintWriter(File file, String csn) ;Creates a new PrintWriter, without automatic line flushing, with the specified file and charset.?
- PrintWriter(OutputStream out) ;Creates a new PrintWriter, without automatic line flushing, from an existing OutputStream.?
- PrintWriter(OutputStream out, boolean autoFlush) ;Creates a new PrintWriter from an existing OutputStream.?
- PrintWriter(String fileName) ;Creates a new PrintWriter, without automatic line flushing, with the specified file name.?
- PrintWriter(String fileName, String csn) ;Creates a new PrintWriter, without automatic line flushing, with the specified file name and charset.?
- PrintWriter(Writer out) ;Creates a new PrintWriter, without automatic line flushing.?
- PrintWriter(Writer out, boolean autoFlush) ;Creates a new PrintWriter.
- 功能
- 提供大量的寫入字符數據的接口,我們大部分情況都是使用的這個類進行寫入操作,同時System.out就是一個PrintWriter對象
PartC?System.in&&System.out&&Scanner
System.in
System類中in屬性定義如下:public final static?InputStream?in = null; in對應一個InputStream類型對象,提供常用二進制流文件訪問方法。in屬性的初始化是由系統完成的,一般用于接收鍵盤或者用戶環境特定的輸入源。System.out
System類中out屬性定義如下:public final static PrintStream out = null; out對應一個PrintStream類型對象,PrintStream內部有一個BufferdWriter對象,具體的操作都是通過該對象完成的!print方法利用String.valueOf方法將數據轉換為String類型的數據;隨后BufferWriter調用writ(String str)方法。out屬性的初始化是由系統完成的,一般對應于用戶的顯示屏設備或者其它用戶環境輸出。Scanner
- 繼承關系:public?final class?Scanner?extends Object?implements?Iterator<String>, Closeable
- 構造器:constructors:
- Scanner(File?source, String charsetName) ;Constructs a new Scanner that produces values scanned from the specified file.?
- Scanner(InputStream?source, String charsetName) ;Constructs a new Scanner that produces values scanned from the specified input stream.?
- Scanner(Path source, String charsetName) ;Constructs a new Scanner that produces values scanned from the specified file.?
- Scanner(Readable?source) ;Constructs a new Scanner that produces values scanned from the specified source.?
- Scanner(String?source) ;Constructs a new Scanner that produces values scanned from the specified string.
- 功能
- A simple?text scanner?which can?parse primitive types and strings?using?regular expressions.
- 使用正則表達式,來讀取一串流數據;對任意數據進行讀取操作,對應的有PrintWriter!
- 默認使用空格符做給分隔符;也可以定制分隔符s.useDelimiter(" |,|\\.")
- next方法以當前非空字符開始,到空字符出現截止為一個數據;(空字符被去掉)
- nextxx()等價于xx var = Xx.valueOf(next()); ?xx是基本數據類型Xx為對應的類,如int與Integer,long與Long
- nextline以當前字符開始到\n換行符出現截止為下一個數據;(換行符不在讀取的string里面)
- 注意:Scanner讀取數據采用的原理使用的是分隔符;每一個nextXX使用的分隔符也是不一樣的;如nextLine和nextInt分隔符肯定不一樣;所以為了避免這樣的問題,建議:使用hasNextXX()判斷是否存在對應類型數據,就使用對應的nextXX()取數據!
PartD 文件操作
PATH?
繼承關系:public?interface?Path ?extends Comparable<Path>, Iterable<Path>, Watchable 是一個抽象類,聲明了一系列對文件路徑的操作(可以是目錄也可以是文件的路徑)
包含方法: Path toAbsolutePath() 絕對路徑 File toFile() 根據路徑得到File對象
Path resolve(Path other) Path resolve(String other)
- 若為絕對路徑則返回絕對路徑,若不是則由this+other共同組成新的路徑
Path resolveSibling(Path other) Path resolveSibling(String other)
- 將參數的path合并到調用該方法的path的父路徑下
Path getParent() 返回父路徑或者null Path getRoot() 返回根路徑或者null Path getFileName() 獲取文件名字
Paths
該類主要使用它的get方法獲得一個Path對象public static Path get(String first, ?String... more) 將一串字符串,利用系統的分隔符組合成一個新的string作為該系統下的文件路徑,返回Path?
Files?
繼承關系:public?final class Files ?extends Object 是一個final類,聲明了一系列public static方法;大部分方法接收的參數為Path類型對象, 然后做相關處理; 包含方法: static long size(Path path) Returns the?size of a file?(in bytes).
//獲取輸入輸出流 static InputStream newInputStream(Path path, OpenOption... options) Opens a file, returning an input stream to read from the file. static OutputStream newOutputStream(Path path, OpenOption... options) ?Opens or?creates?a file, returning an output stream that may be used to write bytes to the file. static BufferedReader newBufferedReader(Path path, Charset cs) Opens a file for reading, returning a BufferedReader that may be used to read text from the file in an?efficient manner. static BufferedWriter newBufferedWriter(Path path, Charset cs, OpenOption... options) Opens or?creates?a file for writing, returning a BufferedWriter that may be used to write text to the file in an?efficient manner.
//文件的輸入輸出流 static Path move(Path source, Path target, CopyOption... options) Move or rename?a file to a target file. static boolean deleteIfExists(Path path) Deletes a file if it exists. static Path copy(Path source, Path target, CopyOption... options) ?Copy a file to a target file.
//創建目錄和文件 static Path createDirectories(Path dir, FileAttribute<?>... attrs) Creates a directory by?creating all nonexistent parent directories first.(自動創建路徑中沒有的目錄) static Path createFile(Path path, FileAttribute<?>... attrs) Creates a new and empty file,?failing if the file already exists.
//創建臨時目錄和文件 static Path createTempDirectory(Path dir, String prefix, FileAttribute<?>... attrs) Creates a new directory?in the specified directory, using the given prefix to generate its name. static Path createTempDirectory(String prefix, FileAttribute<?>... attrs) Creates a new directory?in the default temporary-file directory, using the given prefix to generate its name. static Path createTempFile(Path dir, String prefix, String suffix, FileAttribute<?>... attrs) Creates a new empty file?in the specified directory,?using the given prefix and suffix strings to generate its name. static Path createTempFile(String prefix, String suffix, FileAttribute<?>... attrs) Creates a new empty file?in the default temporary-file directory,?using the given prefix and suffix to generate its name.
//判斷是Path所指的是文件還是目錄
- Files.isDirectory(myPath);
//遍歷一個Path下的 所有路徑(類似 一級路徑)
- DirectoryStream<Path> entries = Files.newDirectoryStream(myPath);
//遍歷一個Path下的所有 子孫路徑(遍歷所有文件)
- Path walkPath = Files.walkFileTree(myPath, new SimpleFileVisitor<Path>(){ ...@override若干方法... };
PartE 補充
接口
- public interface ?Appendable, Closeable, Flushable,Readable接口
- 分別擁有append、close、flush、read方法
- public interface ?CharSequence接口,描述了一個char值序列的基本屬性,有名子類CharBuffer, Segment, String, StringBuffer, StringBuilder
- 擁有charAt(),length(),subSequence(),toString方法
- public interface DataOutput
- 定義了writeXX(); XX為基本數據類型
- public interface DataInput
- 定義了readXX(); XX為基本數據類型
etc:
- RandomAccessFile (是一類可以在文件任意位置進行讀取操作的類)
- ZipInputStream和ZipOutPutStream負責對ZIP文件進行處理,ZIP內部就是一個文件系統
總結
PartA
數據的起點都是二進制數據,即都是InputSteam和OutputStream的子類,這樣的子類有名的有FileInputStream、FileOutputStream; FileInputStream、FileOutputStream兩者的構造器接受的參數為兩種,一為File、二為String代表文件路徑;通過上面步驟我們獲得了一個InputSteam或OutputStream對象,通過最原始的read、write方法或者read(byte[] b, int off, int len)、write(byte[] b, int off, int len)方法讀寫特定字節數的數據; 當然我們可以對上面的最原始的流進行包裝再使用;
- 使用BufferedInputStream和BufferedOutputStream進行包裝,兩者的構造器參數為InputStream或OutputStream對象,使用方式同普通的InputSteam和OutputStream一樣,只是底層實現了緩存效率會高很多。
- 使用ObjectInput和ObjectOutput進行包裝,兩者的構造器參數為InputStream或OutputStream對象,隨后調用readObject、readXX、writeObject、writeXX的方法對java對象進行讀寫,其實就是一個二進制流和一個Object之間的轉換;
- 使用InputStreamReader和OutputStreamReader進行包裝,兩者構造器參數為InputStream或OutputStream對象和charset,隨后調用read(char[] cbuf, int off, int len)、write(char[] cbuf, int off, int len)方法讀寫特定數目的字符,其實這是一個二進制流和字符之間的轉換,使用的編解碼器,可以使用系統默認,也可以在構造對象的時候進行指明;
- 對于Reader和Writer對象,還可以使用BufferedReader和BufferedWriter進行包裝,使得后面的讀寫操作更加高效;底層實現其實就是一次性讀取一塊數據出來,緩存在一個地方,隨后程序讀取數據不是直接從硬盤中的文件中讀取,而是從之前緩存的數據塊中取,當數據快取完的時候,BufferedReader會再從硬盤文件中讀取一整塊數據;
PartB
對于Java中文件的操作,首先需要通過Paths的靜態方法——get(String)、get(URI)獲取到Path,;或者通過Path的resolve(String)和resolveSibling(String)?方法獲取到Path;隨后利用final Class?Files進行一般的文件操作,如刪除復制移動,獲取輸入輸出流等; 此外上面的Path類還有一些很有用的方法,能對路徑進行相關解析; Files除了完成基本的文件操作,還完成了如創建臨時文件夾和臨時文件等操作;PartC
正則表達式——一串特定格式的字符串,用于判斷一個String對象是否滿足這個規則。總結
以上是生活随笔為你收集整理的Java中的IO技术使用总结的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C语言10以内加法口诀表,10以内加减法
- 下一篇: Java okhttp 实现对有道翻译的