日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > java >内容正文

java

Java 文件 IO 操作

發(fā)布時間:2024/7/5 java 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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 對象
import java.io.File;class FileDemo {public static void main(String[] args){File f = new File("file.txt");if(f.exists())f.delete();else{try{f.createNewFile();}catch(Exception e){System.out.println(e.getMessage());}}System.out.println("getName()獲取文件名:"+f.getName());System.out.println("getPath()獲取文件路徑:"+f.getPath());System.out.println("getAbsolutePath()絕對路徑:"+f.getAbsolutePath());System.out.println("getParent()父文件夾名:"+f.getParent());System.out.println("exists()文件存在嗎?"+f.exists());System.out.println("canWrite()文件可寫嗎?"+f.canWrite());System.out.println("canRead()文件可讀嗎?"+f.canRead());System.out.println("isDirectory()是否是目錄?"+f.isDirectory());System.out.println("isFile()是否是文件?"+f.isFile());System.out.println("isAbsolute()是否是絕對路徑名稱?"+f.isAbsolute());System.out.println("lastModified()最后修改時間:"+f.lastModified());System.out.println("length()文件長度-字節(jié)單位:"+f.length());} }

輸出:

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é)單位:0

2. RandomAccessFile類

  • 隨機(jī)跳轉(zhuǎn)到文件的任意位置處讀寫數(shù)據(jù),該類僅限于操作文件
import java.io.File; import java.io.RandomAccessFile; import java.nio.charset.StandardCharsets;class FileDemo {public static void main(String[] args){File f = new File("file.txt");if(f.exists())f.delete();else{try{f.createNewFile();}catch(Exception e){System.out.println(e.getMessage());}}System.out.println("name獲取文件名:"+f.getName());System.out.println("getPath()獲取文件路徑:"+f.getPath());System.out.println("getAbsolutePath()絕對路徑:"+f.getAbsolutePath());System.out.println("getParent()父文件夾名:"+f.getParent());System.out.println("exists()文件存在嗎?"+f.exists());System.out.println("canWrite()文件可寫嗎?"+f.canWrite());System.out.println("canRead()文件可讀嗎?"+f.canRead());System.out.println("isDirectory()是否是目錄?"+f.isDirectory());System.out.println("isFile()是否是文件?"+f.isFile());System.out.println("isAbsolute()是否是絕對路徑名稱?"+f.isAbsolute());System.out.println("lastModified()最后修改時間:"+f.lastModified());System.out.println("length()文件長度-字節(jié)單位:"+f.length());} }class Employee1{String name;int age;final static int LEN = 8;public Employee1(String name, int age){if(name.length() > LEN){name = name.substring(0,8);}else {while(name.length() < LEN)name = name + " ";}this.name = name;this.age = age;} } class RandomFileDemo{public static void main(String[] args) throws Exception{Employee1 e1 = new Employee1("Michael___",18);Employee1 e2 = new Employee1("Ming",19);Employee1 e3 = new Employee1("ABC",20);RandomAccessFile ra = new RandomAccessFile("employee.txt","rw");ra.write(e1.name.getBytes());ra.writeInt(e1.age);ra.write(e2.name.getBytes());ra.writeInt(e2.age);ra.write(e3.name.getBytes());ra.writeInt(e3.age);ra.close();RandomAccessFile raf = new RandomAccessFile("employee.txt","r");int len = 8;raf.skipBytes(12);//跳過第一個員工信息,名字8字節(jié),年齡4字節(jié)System.out.println("第2個員工信息:");String str = "";for(int i = 0; i < len; ++i)str = str+(char)raf.readByte();System.out.println("name: "+str);System.out.println("age: "+raf.readInt());System.out.println("第1個員工的信息:");raf.seek(0);//移動到開始位置str = "";for(int i = 0; i < len; ++i)str = str+(char)raf.readByte();System.out.println("name: "+str.trim());System.out.println("age: "+raf.readInt());System.out.println("第3個員工的信息:");raf.skipBytes(12); // 跳過第2個員工信息str = "";for(int i = 0; i < len; ++i)str = str+(char)raf.readByte();System.out.println("name: "+str.trim());System.out.println("age: "+raf.readInt());raf.close();} }

輸出:

2個員工信息: name: Ming age: 191個員工的信息: name: Michael_ age: 183個員工的信息: name: ABC age: 20進(jìn)程已結(jié)束,退出代碼為 0

3. 流類

  • 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
import java.io.IOException; import java.io.PipedInputStream; import java.io.PipedOutputStream;class Sender extends Thread{private PipedOutputStream out = new PipedOutputStream();public PipedOutputStream getOutputStream() {return out;}public void run(){String s = new String("hello, Michael!");try{out.write(s.getBytes());//寫入,發(fā)送out.close();}catch(IOException e){System.out.println(e.getMessage());}} }class Receiver extends Thread{private PipedInputStream in = new PipedInputStream();public PipedInputStream getInputStream(){return in;}public void run(){String s = null;byte buf[] = new byte[1024];try{int len = in.read(buf);s = new String(buf, 0, len);System.out.println("收到以下訊息:"+s);in.close();}catch(IOException e){System.out.println(e.getMessage());}} }class PipedStreamDemo {public static void main(String[] args){try{Sender sender = new Sender();Receiver receiver = new Receiver();PipedOutputStream out = sender.getOutputStream();PipedInputStream in = receiver.getInputStream();out.connect(in); // 將輸出發(fā)送到輸入sender.start();receiver.start();}catch (IOException e){System.out.println(e.getMessage());}} } // 輸出 : 收到以下訊息:hello, Michael!

3.4 ByteArrayInputStream、ByteArrayOutputStream

  • 如果程序要產(chǎn)生一些臨時文件,可以采用虛擬文件方式實(shí)現(xiàn)(使用這兩個類)
class ByteArrayDemo{public static void main(String[] args) throws Exception{String tmp = "abcdefg**A";byte[] src = tmp.getBytes(); // src 為轉(zhuǎn)換前的內(nèi)存塊ByteArrayInputStream input = new ByteArrayInputStream(src);ByteArrayOutputStream output = new ByteArrayOutputStream();new ByteArrayDemo().transform(input, output);byte[] result = output.toByteArray(); // result為轉(zhuǎn)換后的內(nèi)存塊System.out.println(new String(result));// ABCDEFG**A}public void transform(InputStream in, OutputStream out){int c = 0;try{while((c=in.read()) != -1)//沒有讀到流的結(jié)尾(-1){int C = (int) Character.toUpperCase((char)c);out.write(C);}}catch (IOException e){e.printStackTrace();}} }

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)兩個文件的合并
import java.io.*;class SequenceDemo {public static void main(String[] args) throws IOException {// 兩個文件輸入流FileInputStream in1 = null, in2 = null;// 序列流SequenceInputStream s = null;FileOutputStream out = null;try{File inputfile1 = new File("1.txt");File inputfile2 = new File("2.txt");FileWriter wt = new FileWriter(inputfile1);wt.write("the first file.\nhaha! \n");wt.close();wt = new FileWriter(inputfile2);wt.write("the second file..");wt.close();File outputfile = new File("12.txt");in1 = new FileInputStream(inputfile1);in2 = new FileInputStream(inputfile2);s = new SequenceInputStream(in1, in2); // 合并兩個輸入流out = new FileOutputStream(outputfile);int c;while((c=s.read()) != -1)out.write(c);in1.close();in2.close();s.close();out.close();System.out.println("合并完成!");}catch(IOException e){e.printStackTrace();}} }


3.9 字節(jié)流與字符流的轉(zhuǎn)換

InputstreamReader 用于將一個字節(jié)流中的字節(jié)解碼成字符
OutputstreamWriter 用于將寫入的字符編碼成字節(jié)后寫入一個字節(jié)流

為了效率最高,最好不要直接用這兩個類來讀寫,而是如下方法:

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader;class BufferDemo {public static void main(String[] args){BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));String str = null;while(true){System.out.println("請輸入數(shù)字:");try{str = buf.readLine();}catch(IOException e){e.printStackTrace();}int i = -1;try{i = Integer.parseInt(str);i++;System.out.println("+1 后的數(shù)字為:" + i);break;}catch(Exception e){System.out.println("輸入內(nèi)容不是整數(shù),請重新輸入!");}}} }

輸出:

請輸入數(shù)字: abc 輸入內(nèi)容不是整數(shù),請重新輸入! 請輸入數(shù)字: 123 +1 后的數(shù)字為:124進(jìn)程已結(jié)束,退出代碼為 0

3.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
private transient String name; private transient int age;輸出: name: null, age: 0

總結(jié)

以上是生活随笔為你收集整理的Java 文件 IO 操作的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。