Java?I/O流使用示例詳解
1.java IO包
Java.io 包幾乎包含了所有操作輸入、輸出需要的類。所有這些流類代表了輸入源和輸出目標(biāo)。
Java.io 包中的流支持很多種格式,比如:基本類型、對象、本地化字符集等等。
一個流可以理解為一個數(shù)據(jù)的序列。輸入流表示從一個源讀取數(shù)據(jù),輸出流表示向一個目標(biāo)寫數(shù)據(jù)。
文件依靠流進行傳輸,就像快遞依托于快遞員進行分發(fā)
Java 為 I/O 提供了強大的而靈活的支持,使其更廣泛地應(yīng)用到文件傳輸和網(wǎng)絡(luò)編程中。

下圖是一個描述輸入流和輸出流的類層次圖。

2.創(chuàng)建文件
方式一:
/**
* 創(chuàng)建文件,第一種方式
*/
@Test
public void createFile01() {
String filePath = "D://1.txt";
File file = new File(filePath);
try {
file.createNewFile();
System.out.println("文件創(chuàng)建成功!");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
第二種方式:
/**
* 創(chuàng)建文件,第二種方式
*/
@Test
public void createFile02() {
File parentFile = new File("D:\\");
String fileName = "news.txt";
File file = new File(parentFile, fileName);
try {
file.createNewFile();
System.out.println("文件創(chuàng)建成功!");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
第三種方式:
/**
* 創(chuàng)建文件,第三種方式
*/
@Test
public void createFile03() {
String parentPath = "D:\\";
String fileName = "my.txt";
File file = new File(parentPath, fileName);
try {
file.createNewFile();
System.out.println("文件創(chuàng)建成功!");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
3.獲取文件信息
示例代碼:
/**
* 獲取文件信息
*/
@Test
public void info() {
// 創(chuàng)建文件對象
File file = new File("D:\\news.txt");
// 獲取文件名字
System.out.println(file.getName());
// 獲取文件路徑
System.out.println(file.getAbsolutePath());
// 獲取文件父親目錄
System.out.println(file.getParent());
// 獲取文件大小(字節(jié))
System.out.println(file.length());
// 文件是否存在
System.out.println(file.exists());
// 是不是一個文件
System.out.println(file.isFile());
// 是不是一個目錄
System.out.println(file.isDirectory());
}4.目錄操作
案例一:判斷指定目標(biāo)是否存在,如果存在就刪除
// 判斷指定目標(biāo)是否存在,如果存在就刪除
String filePath = "D:\\news.txt";
File file = new File(filePath);
if (file.exists()) {
if (file.delete()) {
System.out.println("刪除成功!");
} else {
System.out.println("刪除失?。?);
}
} else {
System.out.println("文件不存在!");
}
案例二:判斷目錄是否存在,如果存在即刪除
// 判斷目錄是否存在,如果存在即刪除
String dirPath = "D:\\demo";
File file1 = new File(dirPath);
if (file1.exists()) {
if (file1.delete()) {
System.out.println("刪除成功!");
} else {
System.out.println("刪除失?。?);
}
} else {
System.out.println("目錄不存在!");
}
案例三:判斷指定目錄是否存在,不存在就創(chuàng)建目錄
// 判斷指定目錄是否存在,不存在就創(chuàng)建目錄
String persondir = "D:\\demo\\a\\b\\c";
File file2 = new File(persondir);
if (file2.exists()) {
System.out.println("該目錄存在!");
} else {
if (file2.mkdirs()) {
System.out.println("目錄創(chuàng)建成功!");
} else {
System.out.println("目錄創(chuàng)建失敗!");
}
}
注意:創(chuàng)建多級目錄,使用mkdirs,創(chuàng)建一級目錄使用mkdir
5.字節(jié)輸入流InputStream
InputStream抽象類是所有類字節(jié)輸入流的超類
- FileInputStream 文件輸入流
- BufferedInputStream 緩沖字節(jié)輸入流
- ObjectInputStream 對象字節(jié)輸入流

FileInputStream
文件輸入流,從文件中讀取數(shù)據(jù),示例代碼:
單個字節(jié)的讀取,效率較低:
/**
* read()讀文件
*/
@Test
public void readFile01() throws IOException {
String filePath = "D:\\hacker.txt";
int readData = 0;
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(filePath);
// 讀文件,一個字符一個字符讀取,返回字符的ASCII碼,文件尾部返回-1
while ((readData = fileInputStream.read()) != -1) {
System.out.print((char)readData);
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
// 關(guān)閉流資源
fileInputStream.close();
}
}注意:使用字節(jié)流的方式,無法讀取文件中的中文字符,如需讀取中文字符,最好使用字符流的方式
使用byte數(shù)組的方式讀取,這使得可以讀取中文,并且有效的提升讀取效率:
/**
* read(byte[] b)讀文件
* 支持多字節(jié)讀取,提升效率
*/
@Test
public void readFile02() throws IOException {
String filePath = "D:\\hacker.txt";
int readData = 0;
int readLen = 0;
// 字節(jié)數(shù)組
byte[] bytes = new byte[8]; // 一次最多讀取8個字節(jié)
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(filePath);
// 讀文件,從字節(jié)數(shù)組中直接讀取
// 如果讀取正常,返回實際讀取的字節(jié)數(shù)
while ((readLen = fileInputStream.read(bytes)) != -1) {
System.out.print(new String(bytes, 0, readLen));
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
// 關(guān)閉流資源
fileInputStream.close();
}
}
6.字節(jié)輸出流FileOutputStream

使用示例:(向hacker.txt文件中加入數(shù)據(jù))
/**
* FileOutputStream數(shù)據(jù)寫入文件
* 如果該文件不存在,則創(chuàng)建該文件
*/
@Test
public void writeFile() throws IOException {
String filePath = "D:\\hacker.txt";
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(filePath);
// 寫入一個字節(jié)
// fileOutputStream.write('G');
// 寫入一個字符串
String s = "hello hacker!";
// fileOutputStream.write(s.getBytes());
// 寫入字符串指定范圍的字符
fileOutputStream.write(s.getBytes(),0,3);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} finally {
assert fileOutputStream != null;
fileOutputStream.close();
}
}我們發(fā)現(xiàn),使用這樣的FileOutputStream構(gòu)造器無法實現(xiàn)向文件中追加內(nèi)容,只能進行覆蓋,我們可以在初始化對象的時候這樣解決:
fileOutputStream = new FileOutputStream(filePath,true);
7.模擬文件拷貝
我們可以結(jié)合字節(jié)輸入和輸出流模擬一個文件拷貝的程序:
/**
* 文件拷貝
* 思路:
* 創(chuàng)建文件的輸入流,將文件讀取到程序
* 創(chuàng)建文件的輸出流,將讀取到的文件數(shù)據(jù)寫入到指定的文件
*/
@Test
public void Copy() throws IOException {
String srcFilePath = "D:\\hacker.txt";
String destFilePath = "D:\\hello.txt";
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try {
fileInputStream = new FileInputStream(srcFilePath);
fileOutputStream = new FileOutputStream(destFilePath);
// 定義字節(jié)數(shù)組,提高效率
byte[] buf = new byte[1024];
int readLen = 0;
while ((readLen = fileInputStream.read(buf)) != -1) {
// 邊讀邊寫
fileOutputStream.write(buf, 0, readLen);
}
System.out.println("拷貝成功!");
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (fileInputStream != null){
fileInputStream.close();
}
if (fileOutputStream != null) {
fileOutputStream.close();
}
}
}8.字符輸入流FileReader
字符輸入流FileReader用于從文件中讀取數(shù)據(jù)
示例:
import java.io.FileWriter;
import java.io.IOException;
/**
* 字符輸出流
*/
public class FileWriteTest {
public static void main(String[] args) throws IOException {
String filePath = "D:\\hacker.txt";
// 創(chuàng)建對象
FileWriter fileWriter = null;
try {
char[] chars = {'a', 'b', 'c'};
fileWriter = new FileWriter(filePath, true);
// 寫入單個字符
// fileWriter.write('H');
// 寫入字符數(shù)組
// fileWriter.write(chars);
// 指定數(shù)組的范圍寫入
// fileWriter.write(chars, 0, 2);
// 寫入字符串
// fileWriter.write("解放軍萬歲!");
// 指定字符串的寫入范圍
fileWriter.write("hacker club", 0, 5);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
// FileWriter是需要強制關(guān)閉文件或刷新流的,否則數(shù)據(jù)會保存失敗
fileWriter.close();
}
}
}
9.字符輸出流FileWriter
字符輸出流FileWrite用于寫數(shù)據(jù)到文件中:
示例:
import java.io.FileWriter;
import java.io.IOException;
/**
* 字符輸出流
*/
public class FileWriteTest {
public static void main(String[] args) throws IOException {
String filePath = "D:\\hacker.txt";
// 創(chuàng)建對象
FileWriter fileWriter = null;
try {
char[] chars = {'a', 'b', 'c'};
fileWriter = new FileWriter(filePath, true);
// 寫入單個字符
// fileWriter.write('H');
// 寫入字符數(shù)組
// fileWriter.write(chars);
// 指定數(shù)組的范圍寫入
// fileWriter.write(chars, 0, 2);
// 寫入字符串
// fileWriter.write("解放軍萬歲!");
// 指定字符串的寫入范圍
fileWriter.write("hacker club", 0, 5);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
// FileWriter是需要強制關(guān)閉文件或刷新流的,否則數(shù)據(jù)會保存失敗
fileWriter.close();
}
}
}
使用FileWriter,記得關(guān)閉文件或者刷新流!
到此這篇關(guān)于Java I/O流使用示例詳解的文章就介紹到這了,更多相關(guān)Java I/O流內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java動態(tài)追蹤技術(shù)探究之從JSP到Arthas
這篇文章主要介紹了Java動態(tài)追蹤技術(shù)探究之從JSP到Arthas,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,,需要的朋友可以參考下2019-06-06
Java四舍五入時保留指定小數(shù)位數(shù)的五種方式
這篇文章主要介紹了Java四舍五入時保留指定小數(shù)位數(shù)的五種方式,幫助大家更好的理解和使用Java,感興趣的朋友可以了解下2020-09-09
SpringBoot教程_創(chuàng)建第一個SpringBoot項目
這篇文章主要介紹了SpringBoot教程_創(chuàng)建第一個SpringBoot項目,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06
springboot如何獲取request請求的原始url與post參數(shù)
這篇文章主要介紹了springboot如何獲取request請求的原始url與post參數(shù)問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-12-12

