這篇文章主要介紹java中IO流對文件操作的案例,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
Io流
按照分類 有兩種分類
流向方向: 有輸入流和輸出流
按照操作類型有:字節流和字符流
按照流向方向
字節流的一些操作
//讀文件
FileInputStream fis = new FileInputStream("java.txt");
int temp = fis.read()//一次讀取一個字節
System.out.println(temp); //打印的字母的碼值 讀取完返回-1
System.out.println((char)temp);//打印字母
byte[] arr = new byte[6]; //定義byte數組告訴系統一次讀取幾個字節,減少內存和硬盤之間的通信,可以提高效率
int temp = bis.read(arr); //有參的read方法返回的int值是讀取了幾個字節
System.out.println(new String(arr, 0, temp)); //
//寫文件
FileOutputStream fos = new FileOutputStream("file" + File.separator + "1024.txt",true);
//如果該文件不存在,則會自動創建
//傳入true會在文件內容的后面寫入文字,而不會覆蓋之前的內容
//開發中文件分隔符最好不要直接寫\ 而是寫 File.separator
String msg = "Hello World";
fos.write("\n".getBytes());//換行,并向文件寫入 String.getBytes() 因為要以字節的形式傳入
fos.write(msg.getBytes());
String msg = "好好學習";
//一個漢字占2個字節,向里面一次傳入3個字節會導致亂碼
fos.write(msg.getBytes(), 0, 3);
byte[] arr = new byte[6];//一次性寫這么多字節
int temp = fis.read(arr);
fos.write(arr, 0, temp);
fos.flush();//刷新
//新的jdk7寫法是在try括號()里面寫文件的鏈接, 這樣最后就不用關閉了,會自動關閉
//緩沖輸入流底層默認創建一個大小是8192長度的byte數組
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("java.txt"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("file" + File.separator + "good.txt"));
int temp = bis.read();//temp依然為ascii瑪 每次一個一些練習
利用BufferedInputStream 和 BufferedOutputStream 實現將一個文件copy到另一個文件
package com.wpbxx.stream;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class BufferFileCopy {
public static void main(String[] args) {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream("java.txt"));
bos = new BufferedOutputStream(new FileOutputStream("file" + File.separator + "good.txt"));
int temp;
while((temp = bis.read()) != -1){
bos.write(temp);
}
bos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
bis.close();
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}文件的加密 將一個字節異或一個數字實現 在傳輸時進行文件的加密
package com.wpbxx.stream;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class CodeFile {
public static void main(String[] args) {
//jdk7新寫法
try (
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("圖片.png"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("code.png"));
) {
int temp;
while((temp = bis.read()) != -1){
bos.write(temp ^ 88);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}文件解密
package com.wpbxx.stream;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class DecodeFile {
public static void main(String[] args) {
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream("code.png"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("decode.png"));) {
int temp;
while ((temp = bis.read()) != -1) {
bos.write(temp ^ 88);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}字符流的一些操作 可以解決亂碼的問題
//讀
//注意:字符流不能讀取非文本文件
FileReader fr = new FileReader("java.txt");
int temp;
while ((temp = fr.read()) != -1) {
System.out.println((char) temp); //一次一個字符
}
//使用緩沖字符流
BufferedReader br = new BufferedReader(new FileReader("word.txt"));
String msg;
while((msg = br.readLine()) != null){ //一次可以讀取一行
System.out.println(msg);
}
//寫
FileWriter fw = new FileWriter("word.txt");
fw.write("我喜歡學習java");
fw.write(97);
BufferedWriter bw = new BufferedWriter(new FileWriter("newbuffered.txt"));
bw.write("你好");
bw.newLine();//回車換行
bw.write("java");同樣是copy文件
package com.wpbxx.chario;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
/**
* 使用緩沖流拷貝文件
* 注意:字符流不能讀取非文本文件
*/
public class BufferFileCopy {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("java.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("file" + File.separator + "hellojava.txt"));
) {
String msg;
while((msg = br.readLine()) != null){
bw.write(msg);
bw.newLine();
}
bw.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}通過java中的File類實現對文件的一些操作
File file1 = new File("D:\\hello.txt");
//如果文件存在,就不創建了,返回false,如果不存在就會創建,返回true
System.out.println(file1.createNewFile());
File file2 = new File("D:\\new");
//如果文件夾存在,就不創建了,返回false,如果不存在就會創建,返回true
System.out.println(file2.mkdir());
File file3 = new File("D:\\wpbxx\\1024");
//可以創建多級目錄,如果文件夾存在,就不創建了,返回false,如果不存在就會創建,返回true
System.out.println(file3.mkdirs());
File file4 = new File("D:\\wpbxx\\1024.txt");
//只能創建文件夾
System.out.println(file4.mkdirs());
File file5 = new File("1026.txt");
//如果不寫盤符,會默認在項目的根目錄里面創建
System.out.println(file5.createNewFile());
System.out.println(file5.exists());
//舊名字
File oldFile1 = new File("D:\\world.txt");
//新名字
File newFile1 = new File("D:\\wpbxx\\java.txt");
//如果兩個文件路徑不一致,則會將舊文件剪切到新的文件路徑中再重命名
oldFile1.renameTo(newFile1);
//不會將文件放到回收站中,而是直接刪除
File del = new File("D:\\wpbxx\\java.txt");
File del1 = new File("D:\\wpbxx");
//如果文件夾下有其他文件,則不會刪除
System.out.println(del1.delete());
File file2 = new File("D:\\new.txt");
//判斷是否是文件夾
System.out.println(file2.isDirectory());
//判斷是否是文件
System.out.println(file2.isFile());
//判斷文件是否存在
System.out.println(file2.exists());
File file3 = new File("D:\\hidden");
//判斷文件是否隱藏
System.out.println(file3.isHidden());
File file1 = new File("1024.txt");
//查看絕對路徑
System.out.println(file1.getAbsolutePath());
//文件的大小,單位是字節
System.out.println(file1.length());
//最后修改時間
Date date = new Date(file1.lastModified());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(sdf.format(date));
File file2 = new File("F:\\wpbxx\\代碼\\code\\chapter-08");
//獲取目錄下的同級文件或文件夾的名稱
String[] nameArray = file2.list();
for(String name : nameArray){
System.out.println(name);
}幾個小練習
package com.wpbxx.exercise;
import java.io.File;
import java.util.Scanner;
/**
* 問題:從鍵盤接收一個路徑,將這個路徑下的所有文件和文件夾的名字按照層級打印。
* 例如:
* wpbxx
* java
* XXX.java
* XXX.jpg
* php
* XXX.php
* readme.txt
*
* 分析:獲取路徑File對象中的File數組
* 遍歷數組,取得File對象
* 打印文件或文件夾的名字
* 如果是一個文件夾的話,使用遞歸重復上面的操作
*/
public class FileNames {
//用來記錄縮進的次數
private static int count = 0;
public static void main(String[] args) {
File file = getFile();
getFileNames(file);
}
//每次調用該方法時,說明進入到一個新的文件夾的內部,需要增加一個縮進
private static void getFileNames(File file) {
//獲取路徑File對象中的File數組
File[] fileArray = file.listFiles();
//遍歷數組,取得File對象
for(int i=0; i<fileArray.length; i++){
//通過遍歷count來控制打印幾個縮進
for(int j=0; j<count; j++){
System.out.print("\t");
}
//打印文件或文件夾的名字
System.out.println(fileArray[i]);
//如果是一個文件夾的話,使用遞歸重復上面的操作
if(fileArray[i].isDirectory()){
count++;
getFileNames(fileArray[i]);//數組遍歷完最后一個File對象時,說明當前文件夾已經遍歷結束,需要做自減運算
count--;
}
}
}
//獲取用戶輸入路徑的File對象
private static File getFile() {
System.out.println("請輸入一個文件夾路徑:");
Scanner sc = new Scanner(System.in);
//獲取用戶輸入的路徑,用戶輸入的路徑有可能是錯誤的,需要進行判斷
while(true){
String input = sc.nextLine();
File file = new File(input);
if(!file.exists()){
System.out.println("您輸入的文件路徑有誤,請重新輸入文件路徑:");
}else if(file.isFile()){
//如果用戶輸入的路徑是一個文件
System.out.println("您輸入的路徑是一個文件,請輸入一個文件夾的路徑");
}else{
return file;
}
}
}
}package com.wpbxx.exercise;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* 問題:收費版軟件有試用次數,利用IO流的知識,模擬一個可以試用3次的功能,打開3次之后提示用戶購買正版軟件
*
* 分析:將試用的次數做加密處理后寫到txt文件中
* 使用IO流相關的知識將txt文件中的內容讀取到內存中
* 如果讀取的內容小于0時提示用戶購買正版軟件
* 如果大于0小于等于3時,將試用次數做自減運算之后寫出到txt文件中
*/
public class Trial {
public static void main(String[] args) {
//code();
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream("src" + File.separator + "com"
+ File.separator + "monkey1024" + File.separator + "exercise" + File.separator + "config.txt"));
int temp = bis.read();
//解密處理
int count = temp ^ 66;
if(count > 0 && count <= 3){
count--;
System.out.println("您的試用次數還剩余" + count + "次");
bos = new BufferedOutputStream(new FileOutputStream("src" + File.separator + "com"
+ File.separator + "monkey1024" + File.separator + "exercise" + File.separator + "config.txt"));
//做加密處理
bos.write(count ^ 66);
bos.flush();
}else{
System.out.println("您的試用次數已超出限制,請購買正版軟件!");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
//避免出現空指針
if(bis != null){
bis.close();
}
if(bos != null){
bos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
//試用次數加密處理
private static void code() {
BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(new FileOutputStream("src" + File.separator + "com"
+ File.separator + "monkey1024" + File.separator + "exercise" + File.separator + "config.txt"));
//加密處理
bos.write(3 ^ 66);
bos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
//避免出現空指針異常
if(bos != null){
bos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}package com.wpbxx.exercise;
import java.io.File;
/**
* 問題:統計項目根目錄下以.txt結尾的文件數量,并將文件名打印出來
* 分析:獲取項目根目錄下的文件名
* 對文件名進行判斷是否是以.txt結尾
*/
public class FindTxt {
public static void main(String[] args) {
File file = new File("F:\\wpbxx\\01-JavaSE\\代碼\\code\\chapter-08");
File[] fileArray = file.listFiles(); //返回一個File列表就是該目錄下的File列表
//統計出現次數
int count = 0;
for(File name : fileArray){
String s = name.toString();
//判斷是否是以.txt文件結尾
if(s.endsWith(".txt")){
if(name.isFile()){
count++;
System.out.println(name);
}
}
}
System.out.println("以.txt文件結尾的數量是" + count + "個");
}
}package com.monkey1024.file;
import java.io.File;
import java.io.FilenameFilter;
/**
* 問題:統計項目根目錄下以.txt結尾的文件數量,并將文件名打印出來
* 使用文件過濾器實現上述需求
*/
public class FilenameFilterTest01 {
public static void main(String[] args) {
File file = new File("F:\\monkey1024\\01-JavaSE\\代碼\\code\\chapter-08");
String[] nameArray = file.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name){
//獲取根目錄下每個文件的File對象
File file1 = new File(dir, name);
//編寫篩選條件
return file1.isFile() && file1.getName().endsWith(".txt");
}
});
System.out.println("以.txt結尾的文件個數是" + nameArray.length + "個");
for(String name : nameArray){
System.out.println(name);
}
}
}package com.wpbxx.file;
import java.io.File;
import java.io.FilenameFilter;
/**
* 問題:統計項目根目錄下以.txt結尾的文件數量,并將文件名打印出來
* 使用文件過濾器實現上述需求
*/
public class FilenameFilterTest01 {
public static void main(String[] args) {
File file = new File("F:\\wpbxx\\01-JavaSE\\代碼\\code\\chapter-08");
String[] nameArray = file.list(new FilenameFilter() {//重寫accept方法
@Override
public boolean accept(File dir, String name){//將過濾的規則寫進來
//獲取根目錄下每個文件的File對象
File file1 = new File(dir, name);
//編寫篩選條件
return file1.isFile() && file1.getName().endsWith(".txt");
}
});
System.out.println("以.txt結尾的文件個數是" + nameArray.length + "個");
for(String name : nameArray){
System.out.println(name);
}
}
}對對象的讀取
為啥要對對象讀???
平時我們在Java內存中的對象,是無 法進行IO操作或者網絡通信的,因為在進行IO操作或者網絡通信的時候,人家根本不知道內存中的對象是個什么東西,因此必須將對象以某種方式表示出來,即 存儲對象中的狀態。一個Java對象的表示有各種各樣的方式,Java本身也提供給了用戶一種表示對象的方式,那就是序列化。換句話說,序列化只是表示對 象的一種方式而已。OK,有了序列化,那么必然有反序列化,我們先看一下序列化、反序列化是什么意思。
序列化:將一個對象轉換成一串二進制表示的字節數組,通過保存或轉移這些字節數據來達到持久化的目的。
反序列化:將字節數組重新構造成對象。
序列化只需要實現java.io.Serializable接口就可以了。序列化的時候有一個serialVersionUID參數,Java序列化機制是通過在運行時判斷類的serialVersionUID來驗證版本一致性的。 在進行反序列化,Java虛擬機會把傳過來的字節流中的serialVersionUID和本地相應實體類的serialVersionUID進行比較, 如果相同就認為是一致的實體類,可以進行反序列化,否則Java虛擬機會拒絕對這個實體類進行反序列化并拋出異常。serialVersionUID有兩 種生成方式:
如果一個類的對象支持序列化和反序列化,需要實現Serializable,Serializable中沒有任何方法,只是相當于一個標記
有一個類
package com.monkey1024.serializable;
import java.io.Serializable;
/**
* 如果一個類的對象支持序列化和反序列化,需要實現Serializable
* Serializable中沒有任何方法
*/
public class Student implements Serializable{
/**
* 自動生成序列化版本號
*/
private static final long serialVersionUID = -716323668524282676L;
private String name;
//添加屬性后,使用反序列化時會報出InvalidClassException
//transient修飾的變量不會被序列化
transient private int age;
private boolean sex;
public boolean isSex() {
return sex;
}
public void setSex(boolean sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}然后我們對這個類進行序列化和反序列化
Student zhangsan = new Student();
zhangsan.setName("張三");
zhangsan.setAge(20);
//寫
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("zhangsan"));
oos.writeObject(zhangsan);
oos.flush();
//讀
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("zhangsan"));
Student s = (Student)ois.readObject();
System.out.println(s.getName());
System.out.println(s.getAge());以上是java中IO流對文件操作的案例的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。