Java 文件 IO 操作
生活随笔
收集整理的這篇文章主要介紹了
Java 文件 IO 操作
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
文章目錄
- 1. File類
- 2. RandomAccessFile類
- 3. 流類
- 3.1 字節(jié)流
- 3.2 字符流
- 3.3 管道流
- 3.4 ByteArrayInputStream、ByteArrayOutputStream
- 3.5 System.in、System.out
- 3.6 打印流 PrintStream
- 3.7 DataInputStream、DataOutputStream
- 3.8 合并流
- 3.9 字節(jié)流與字符流的轉(zhuǎn)換
- 3.10 IO包類層次關(guān)系
- 4. 字符編碼
- 5. 對象序列化
1. File類
File 類 是 java.io 包中唯一代表磁盤文件本身的對象
- File(String dirPath) 構(gòu)造生成 File 對象
輸出:
getName()獲取文件名:file.txt getPath()獲取文件路徑:file.txt getAbsolutePath()絕對路徑:D:\gitcode\java_learning\file.txt getParent()父文件夾名:null exists()文件存在嗎?true canWrite()文件可寫嗎?true canRead()文件可讀嗎?true isDirectory()是否是目錄?false isFile()是否是文件?true isAbsolute()是否是絕對路徑名稱?false lastModified()最后修改時間:1614680366121 length()文件長度-字節(jié)單位:02. RandomAccessFile類
- 隨機(jī)跳轉(zhuǎn)到文件的任意位置處讀寫數(shù)據(jù),該類僅限于操作文件
輸出:
第2個員工信息: name: Ming age: 19 第1個員工的信息: name: Michael_ age: 18 第3個員工的信息: name: ABC age: 20進(jìn)程已結(jié)束,退出代碼為 03. 流類
- InputStream、OutputStream 字節(jié)流(處理字節(jié)、二進(jìn)制對象)
- Reader、Writer 字符流(字符、字符串)
處理流程:
- 使用 File 類找到文件
- 通過 File 類對象實(shí)例化 流的子類
- 進(jìn)行字節(jié)、字符的讀寫操作
- 關(guān)閉文件流
3.1 字節(jié)流
import java.io.*;class IoDemo {public static void main(String[] args){// 寫文件File f = new File("file.txt");FileOutputStream out = null;try{out = new FileOutputStream(f);}catch (FileNotFoundException e){e.printStackTrace();}byte b[] = "Hello Michael!".getBytes();try{out.write(b);}catch (IOException e){e.printStackTrace();}try{out.close();}catch (IOException e){e.printStackTrace();}// 讀文件FileInputStream in = null;try{in = new FileInputStream(f);}catch (FileNotFoundException e){e.printStackTrace();}byte b1[] = new byte[1024];//開辟空間接收文件讀入進(jìn)來int i = 0;try{i = in.read(b1);//返回讀入數(shù)據(jù)的個數(shù)}catch(IOException e){e.printStackTrace();}try{in.close();}catch (IOException e){e.printStackTrace();}System.out.println(new String(b,0,i));// Hello Michael!} }3.2 字符流
class CharDemo {public static void main(String[] args){// 寫文件File f = new File("file.txt");FileWriter out = null;try{out = new FileWriter(f);}catch (IOException e){e.printStackTrace();}String str= "Hello Michael!";try{out.write(str);}catch (IOException e){e.printStackTrace();}try{out.close();}catch (IOException e){e.printStackTrace();}// 讀文件FileReader in = null;try{in = new FileReader(f);}catch (FileNotFoundException e){e.printStackTrace();}char c1[] = new char[1024];//開辟空間接收文件讀入進(jìn)來int i = 0;try{i = in.read(c1);//返回讀入數(shù)據(jù)的個數(shù)}catch(IOException e){e.printStackTrace();}try{in.close();}catch (IOException e){e.printStackTrace();}System.out.println(new String(c1,0,i));// Hello Michael!} }3.3 管道流
- 主要用于連接兩個線程間的通信
- PipedInputStream、PipedOutputStream、PipedReader、PipedWriter
3.4 ByteArrayInputStream、ByteArrayOutputStream
- 如果程序要產(chǎn)生一些臨時文件,可以采用虛擬文件方式實(shí)現(xiàn)(使用這兩個類)
3.5 System.in、System.out
- System.in 對應(yīng)鍵盤,屬于 InputStream
- Sytem.out 對應(yīng)顯示器,屬于 PrintStream
3.6 打印流 PrintStream
class SystemPrintDemo{public static void main(String[] args){PrintWriter out = new PrintWriter(System.out);out.print("hello Michael");out.println("hello Michael");out.close();} }輸出:
hello Michaelhello Michael進(jìn)程已結(jié)束,退出代碼為 0 class FilePrint{public static void main(String[] args){PrintWriter out = null;File f = new File("file1.txt");try{out = new PrintWriter(new FileWriter(f));}catch (IOException e){e.printStackTrace();}out.print("Hello Michael!!!");out.close();} }3.7 DataInputStream、DataOutputStream
import java.io.*;class DataStreamDemo {public static void main(String[] args) throws Exception{// 將數(shù)據(jù)寫入文件DataOutputStream out = new DataOutputStream(new FileOutputStream("order.txt"));double prices[] = {18.99, 9.22, 14.22, 5.22, 4.21};int units[] = {10, 10, 20, 39, 40};String [] name = {"T恤衫", "杯子", "洋娃娃", "大頭針", "鑰匙鏈"};for(int i = 0; i < prices.length; ++i){//寫入價格out.writeDouble(prices[i]);out.writeChar('\t');//寫入數(shù)目out.writeInt(units[i]);out.writeChar('\t');//寫入產(chǎn)品名稱,行尾換行out.writeChars(name[i]);out.writeChar('\n');}out.close();//將數(shù)據(jù)讀出DataInputStream in = new DataInputStream(new FileInputStream("order.txt"));double price;int unit;StringBuffer tempName;double total = 0.0;try{ // 文本讀完后會拋出 EOF 異常while(true){price = in.readDouble();in.readChar();//跳過tabunit = in.readInt();in.readChar();//跳過tabchar c;tempName = new StringBuffer();while((c=in.readChar()) != '\n')tempName.append(c);System.out.println("訂單信息:" + "產(chǎn)品名稱:" + tempName+ ", \t 數(shù)量:" + unit + ", \t 價格" + price);total += unit*price;}}catch (EOFException e){System.out.println("\n 共需要:" + total + "元");}in.close();} }輸出:
3.8 合并流
- SequenceInputStream 類,可以實(shí)現(xiàn)兩個文件的合并
3.9 字節(jié)流與字符流的轉(zhuǎn)換
InputstreamReader 用于將一個字節(jié)流中的字節(jié)解碼成字符
OutputstreamWriter 用于將寫入的字符編碼成字節(jié)后寫入一個字節(jié)流
為了效率最高,最好不要直接用這兩個類來讀寫,而是如下方法:
輸出:
請輸入數(shù)字: abc 輸入內(nèi)容不是整數(shù),請重新輸入! 請輸入數(shù)字: 123 +1 后的數(shù)字為:124進(jìn)程已結(jié)束,退出代碼為 03.10 IO包類層次關(guān)系
4. 字符編碼
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream;class EncodingDemo {public static void main(String[] args){try {byte[] b = "一起來學(xué)習(xí)Java吧!".getBytes("GB2312");OutputStream out = new FileOutputStream(new File("encode.txt"));out.write(b);out.close();}catch (IOException e){System.out.println(e.getMessage());}} }
5. 對象序列化
對象序列化,是指將對象轉(zhuǎn)換成二進(jìn)制數(shù)據(jù)流的一種實(shí)現(xiàn)手段。
通過將對象序列化,可以方便地實(shí)現(xiàn)對象的傳輸及保存。
在Java中提供有 ObjectInputStream 與 ObjectOutputStream 這兩個類用于序列化對象的操作。
ObjectInputStream 與 ObjectOutputStream 這兩個類,用于幫助開發(fā)者完成保存和讀取對象成員變量取值的過程,但要求讀寫或存儲的對象必須實(shí)現(xiàn)了 Serializable 接口,但 Serializable 接口中沒有定義任何方法,僅僅被用做一種標(biāo)記,以被編譯器作特殊處理。
import java.io.*;class Person6 implements Serializable{ // 實(shí)現(xiàn)了Serializable,可序列化private String name;private int age;public Person6(String name, int age){this.name = name;this.age = age;}public String toString(){return "name: " + name + ", age: " + age;} }public class SerializableDemo {public static void serialize(File f) throws Exception{OutputStream outputFile = new FileOutputStream(f);ObjectOutputStream cout = new ObjectOutputStream(outputFile);cout.writeObject(new Person6("Michael", 18));cout.close();}public static void deserialize(File f) throws Exception{InputStream inputFile = new FileInputStream(f);ObjectInputStream cin = new ObjectInputStream(inputFile);Person6 p = (Person6) cin.readObject();System.out.println(p);// name: Michael, age: 18}public static void main(String[] args) throws Exception{File f = new File("SerializedPersonInfo.txt");serialize(f);deserialize(f);} }- 如果不希望類中屬性被序列化,加入關(guān)鍵字 transient
總結(jié)
以上是生活随笔為你收集整理的Java 文件 IO 操作的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数据库和ORMS:使用SQLAlchem
- 下一篇: Java可靠性测试fit_Java Pa