Java中流(Stream)、文件(File)和IO示例詳解
一、Java 流(Stream)、文件(File)和IO概念和關(guān)系
Java 中的流(Stream)、文件(File)和 IO 之間是緊密關(guān)聯(lián)但又各有側(cè)重的概念,它們共同構(gòu)成了 Java 輸入輸出系統(tǒng)的核心??梢杂?quot;工具-對(duì)象-操作"的關(guān)系來(lái)理解:
IO 是總稱(chēng)
IO(Input/Output,輸入/輸出)是所有數(shù)據(jù)傳輸操作的統(tǒng)稱(chēng),涵蓋了程序與外部設(shè)備(文件、網(wǎng)絡(luò)、鍵盤(pán)等)之間的數(shù)據(jù)交換。
流(Stream)和文件(File)都是實(shí)現(xiàn) IO 操作的具體方式或操作對(duì)象。File 是操作的實(shí)體
java.io.File類(lèi)代表文件系統(tǒng)中的一個(gè)文件或目錄,是 IO 操作的具體對(duì)象。
但它本身不能直接讀寫(xiě)數(shù)據(jù),只能描述文件的屬性(如路徑、大小、是否存在等),并提供創(chuàng)建、刪除等文件管理功能。Stream 是操作的工具
流(Stream)是連接程序與外部數(shù)據(jù)源(包括 File)的數(shù)據(jù)傳輸通道,是實(shí)現(xiàn) IO 操作的核心工具。
當(dāng)需要讀寫(xiě) File 中的內(nèi)容時(shí),必須通過(guò)流來(lái)實(shí)現(xiàn):- 讀文件:用輸入流(如
FileInputStream)從 File 中讀取數(shù)據(jù)到程序 - 寫(xiě)文件:用輸出流(如
FileOutputStream)從程序?qū)懭霐?shù)據(jù)到 File
- 讀文件:用輸入流(如
三者協(xié)作關(guān)系
一個(gè)典型的文件 IO 操作流程是:
創(chuàng)建 File 對(duì)象(指定要操作的文件) → 通過(guò)流連接 File(如 new FileInputStream(file)) → 通過(guò)流進(jìn)行 IO 操作(讀/寫(xiě)數(shù)據(jù))
二、讀寫(xiě)文件
2.1 操作文件時(shí)涉及的字符流和字節(jié)流的概念介紹:
字節(jié)流
基本概念:字節(jié)流是以字節(jié)(8位二進(jìn)制數(shù)據(jù))作為基本處理單位的流,它能對(duì)各種類(lèi)型的文件進(jìn)行讀寫(xiě)操作,因?yàn)橛?jì)算機(jī)中所有的數(shù)據(jù)在底層都是以字節(jié)形式存儲(chǔ)和傳輸?shù)?。字?jié)流可以直接操作二進(jìn)制數(shù)據(jù),無(wú)論是文本文件還是非文本文件(如圖像、音頻、視頻等)都能處理。
字節(jié)輸入流(InputStream):
用于從文件等數(shù)據(jù)源讀取字節(jié)數(shù)據(jù)到程序中。它是字節(jié)流輸入操作的抽象基類(lèi),提供了如read()等基礎(chǔ)方法用于讀取字節(jié)數(shù)據(jù)。字節(jié)輸出流(OutputStream):
負(fù)責(zé)將程序中的字節(jié)數(shù)據(jù)寫(xiě)入到文件等目標(biāo)數(shù)據(jù)源中。它是字節(jié)流輸出操作的抽象基類(lèi),提供了write()等方法用于寫(xiě)入字節(jié)數(shù)據(jù)。
字符流
基本概念:字符流以字符(一般是16位的Unicode編碼字符)為基本處理單位,更側(cè)重于處理文本文件,它在讀寫(xiě)文本時(shí)會(huì)按照字符編碼規(guī)范進(jìn)行轉(zhuǎn)換,能更好地保證文本內(nèi)容的正確讀寫(xiě),還能方便地按行等文本特性進(jìn)行操作。
字符輸入流(Reader):
用于從文件等數(shù)據(jù)源讀取字符數(shù)據(jù)到程序里,是字符流輸入操作的抽象基類(lèi),提供了read()等方法來(lái)獲取字符數(shù)據(jù)。字符輸出流(Writer):
主要用于將程序中的字符數(shù)據(jù)寫(xiě)入到文件等目標(biāo)數(shù)據(jù)源中,是字符流輸出操作的抽象基類(lèi),具備write()等方法來(lái)輸出字符數(shù)據(jù)。
字節(jié)流、字符流常用關(guān)系圖

2.2 字節(jié)流常用方法
字節(jié)流常用于處理二進(jìn)制數(shù)據(jù),例如文件、圖像、時(shí)頻。
| 類(lèi)名 | 類(lèi)型 | 描述 |
|---|---|---|
| InputStream | 抽象類(lèi)(輸入流) | 所有字節(jié)輸入流的超類(lèi),處理字節(jié)的輸入操作 |
| OutputStream | 抽象類(lèi)(輸出流) | 所有字節(jié)輸出流的超類(lèi),處理字節(jié)的輸出操作 |
| FileInputStream | 輸入流 | 從文件中讀取字節(jié)數(shù)據(jù) |
| FileOutputStream | 輸出流 | 將字節(jié)數(shù)據(jù)寫(xiě)入文件 |
| BufferedInputStream | 輸入流 | 為字節(jié)輸入流提供緩沖功能,提高讀取效率 |
| BufferedOutputStream | 輸出流 | 為字節(jié)輸出流提供緩沖功能,提高寫(xiě)入效率 |
| ByteArrayInputStream | 輸入流 | 將內(nèi)存中的字節(jié)數(shù)組作為輸入源 |
| ByteArrayOutputStream | 輸出流 | 將數(shù)據(jù)寫(xiě)入到內(nèi)存中的字節(jié)數(shù)組 |
| DataInputStream | 輸入流 | 允許從輸入流中讀取Java原生數(shù)據(jù)類(lèi)型(如int、float、boolean等) |
| DataOutputStream | 輸出流 | 允許向輸出流中寫(xiě)入Java原生數(shù)據(jù)類(lèi)型 |
| ObjectInputStream | 輸入流 | 從輸入流中讀取序列化對(duì)象 |
| ObjectOutputStream | 輸出流 | 將對(duì)象序列化并寫(xiě)入輸出流中 |
| PipedInputStream | 輸入流 | 用于在管道中讀取字節(jié)數(shù)據(jù),通常與PipedOutputStream配合使用 |
| PipedOutputStream | 輸出流 | 用于在管道中寫(xiě)入字節(jié)數(shù)據(jù),通常與PipedInputStream配合使用 |
| FilterInputStream | 輸入流 | 字節(jié)輸入流的包裝類(lèi),用于對(duì)其他輸入流進(jìn)行過(guò)濾處理 |
| FilterOutputStream | 輸出流 | 字節(jié)輸出流的包裝類(lèi),用于對(duì)其他輸出流進(jìn)行過(guò)濾處理 |
| SequenceInputStream | 輸入流 | 將多個(gè)輸入流串聯(lián)為一個(gè)輸入流進(jìn)行處理 |
以下是基于表格中各類(lèi)字節(jié)流的讀寫(xiě)文件示例,涵蓋不同場(chǎng)景的文件操作:
1. FileInputStream/FileOutputStream(基礎(chǔ)文件讀寫(xiě))
FileInputStream 和 FileOutputStream 是 Java IO 中用于直接操作文件的字節(jié)流,專(zhuān)門(mén)負(fù)責(zé)從文件讀取字節(jié)數(shù)據(jù)和向文件寫(xiě)入字節(jié)數(shù)據(jù),是處理文件字節(jié)流的基礎(chǔ)類(lèi)。
import java.io.*;
public class Main {
public static void main(String[] args) {
// 寫(xiě)入文件
try {
FileOutputStream fileOutputStream =new FileOutputStream("file.txt");
String data="Hello byteStream!";
fileOutputStream.write(data.getBytes());
fileOutputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
FileInputStream fileInputStream =new FileInputStream("file.txt");
int c;
while((c=fileInputStream.read())!=-1){
System.out.print((char)c);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

2. BufferedInputStream/BufferedOutputStream(緩沖流高效讀寫(xiě))
BufferedInputStream 和 BufferedOutputStream 是 Java IO 中提供緩沖功能的過(guò)濾流,它們通過(guò)在內(nèi)存中維護(hù)緩沖區(qū)來(lái)減少物理 I/O 操作次數(shù),從而顯著提升讀寫(xiě)效率。
import java.io.*;
public class Main {
public static void main(String[] args) {
// 寫(xiě)入文件
try {
BufferedOutputStream bufferedOutputStream =new BufferedOutputStream(new FileOutputStream("file.txt"));
String data="Hello byteStream!";
bufferedOutputStream.write(data.getBytes());
bufferedOutputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
BufferedInputStream bufferedInputStream =new BufferedInputStream(new FileInputStream("file.txt"));
int c;
while((c=bufferedInputStream.read())!=-1){
System.out.print((char)c);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
3. DataInputStream/DataOutputStream(讀寫(xiě)基本數(shù)據(jù)類(lèi)型)
DataInputStream 和 DataOutputStream 是 Java IO 中用于讀寫(xiě)基本數(shù)據(jù)類(lèi)型的過(guò)濾流,它們可以直接操作 Java 原生數(shù)據(jù)類(lèi)型(如 int、double、boolean 等),無(wú)需手動(dòng)處理字節(jié)轉(zhuǎn)換,簡(jiǎn)化了基本類(lèi)型數(shù)據(jù)的讀寫(xiě)操作。
import java.io.*;
public class Main {
public static void main(String[] args) {
// 寫(xiě)入文件
try {
DataOutputStream bufferedOutputStream =new DataOutputStream(new FileOutputStream("file.bat"));
bufferedOutputStream.writeInt(100); // 寫(xiě)入整數(shù)
bufferedOutputStream.writeDouble(3.14); // 寫(xiě)入雙精度浮點(diǎn)數(shù)
bufferedOutputStream.writeUTF("Hello byteStream!");
bufferedOutputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
DataInputStream bufferedInputStream =new DataInputStream(new FileInputStream("file.bat"));
System.out.println(bufferedInputStream.readInt());
System.out.println(bufferedInputStream.readDouble());
System.out.println(bufferedInputStream.readUTF());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

4. ObjectInputStream/ObjectOutputStream(對(duì)象序列化)
ObjectInputStream 和 ObjectOutputStream 是 Java 中用于對(duì)象序列化與反序列化的字節(jié)流,主要功能是將內(nèi)存中的 Java 對(duì)象轉(zhuǎn)換為字節(jié)序列(序列化)并寫(xiě)入流中,或從流中讀取字節(jié)序列并恢復(fù)為 Java 對(duì)象(反序列化)。
import java.io.*;
// 需實(shí)現(xiàn)Serializable接口才能被序列化
class User implements Serializable {
private String name;
private int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "User{name='" + name + "', age=" + age + "}";
}
}
public class Main {
public static void main(String[] args) {
// 序列化對(duì)象寫(xiě)入文件
try {
ObjectOutputStream objectOutputStream =new ObjectOutputStream(new FileOutputStream("file.obj"));
User user=new User("Alice", 18);
objectOutputStream.writeObject(user);
objectOutputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
ObjectInputStream objectInputStream=new ObjectInputStream(new FileInputStream("file.obj"));
User user=(User) objectInputStream.readObject();
System.out.println(user);
} catch (IOException | ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
}

5.ByteArrayOutputStream(內(nèi)存字節(jié)數(shù)組讀寫(xiě))
它可以將數(shù)據(jù)寫(xiě)入內(nèi)存中的字節(jié)數(shù)組緩沖區(qū)。創(chuàng)建后可以用來(lái)收集和操作字節(jié)數(shù)據(jù),常用于臨時(shí)存儲(chǔ)或處理二進(jìn)制數(shù)據(jù)。
public class Main {
public static void main(String[] args) {
ByteArrayOutputStream byteArrayOutputStream =new ByteArrayOutputStream();
byte [] bytes = new byte[1024];
try {
bytes[0]=(byte) 'H';
bytes[1]=(byte) 'e';
bytes[2]=(byte) 'l';
bytes[3]=(byte) 'l';
bytes[4]=(byte) 'o';
byteArrayOutputStream.write(bytes,0,5);
byteArrayOutputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
byte [] bytes1 = new byte[1024];
int c;
try{
while ((c=byteArrayInputStream.read(bytes1))!=-1){
System.out.println(new String(bytes1, 0, c));
}
}catch (IOException e){
throw new RuntimeException(e);
}
}
}

6. SequenceInputStream(合并多個(gè)輸入流)
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
SequenceInputStream sequenceInputStream =new SequenceInputStream(new FileInputStream("file.txt"),new FileInputStream("test.txt"));
int c;
while((c=sequenceInputStream.read())!=-1){
System.out.print((char)c);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
7. FilterInputStream/FilterOutStream
FilterInputStream 和 FilterOutputStream 是 Java IO 中的過(guò)濾流基類(lèi),屬于裝飾器模式(Decorator Pattern)的典型實(shí)現(xiàn),用于對(duì)現(xiàn)有流進(jìn)行功能擴(kuò)展或增強(qiáng)。
import java.io.FilterInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.IOException;
// 自定義過(guò)濾輸入流:轉(zhuǎn)換為大寫(xiě)
class UpperCaseInputStream extends FilterInputStream {
/**
* Creates a <code>FilterInputStream</code>
* by assigning the argument <code>in</code>
* to the field <code>this.in</code> so as
* to remember it for later use.
*
* @param in the underlying input stream, or <code>null</code> if
* this instance is to be created without an underlying stream.
*/
protected UpperCaseInputStream(InputStream in) {
super(in);
}
@Override
public int read(byte [] b,int off,int len ) throws IOException {
int result = super.read(b, off, len);//讀取的字節(jié)數(shù)
if(result!=-1){
for(int i=off;i<off+result;i++){
b[i]= (byte) Character.toUpperCase((char)b[i]);
}
}
return result;
}
}
public class Main {
public static void main(String[] args) {
try {
UpperCaseInputStream
upperCaseInputStream =new UpperCaseInputStream(new FileInputStream("file.txt"));
int c;
byte [] bytes=new byte[1024];
while((c=upperCaseInputStream.read(bytes))!=-1){
System.out.print(new String(bytes,0,c));
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

8.pipedOutputStream/pipedInputStream
PipedOutputStream 和 PipedInputStream 是 Java 中用于線(xiàn)程間通信的管道流,二者必須配合使用,形成 “生產(chǎn)者 - 消費(fèi)者” 模式的數(shù)據(jù)傳輸通道。
public class Main {
public static void main(String[] args) {
PipedOutputStream pipedOutputStream =new PipedOutputStream();
PipedInputStream pipedInputStream;
try {
pipedInputStream =new PipedInputStream(pipedOutputStream);
} catch (IOException e) {
throw new RuntimeException(e);
}
new Thread(new Runnable() {
@Override
public void run() {
try {
pipedOutputStream.write("Hello byteStream!".getBytes());
pipedOutputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}).start();
new Thread(new Runnable(){
@Override
public void run() {
try {
int c;
while((c=pipedInputStream.read())!=-1){
System.out.print((char)c);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}).start();
}
}
2.3 字符流常用方法
字符流常用于處理文本數(shù)據(jù)。
| 類(lèi)名 | 類(lèi)型 | 描述 |
|---|---|---|
| Reader | 抽象類(lèi)(輸入流) | 所有字符輸入流的超類(lèi),處理字符的輸入操作 |
| Writer | 抽象類(lèi)(輸出流) | 所有字符輸出流的超類(lèi),處理字符的輸出操作 |
| FileReader | 輸入流 | 從文件中讀取字符數(shù)據(jù) |
| FileWriter | 輸出流 | 將字符數(shù)據(jù)寫(xiě)入文件 |
| BufferedReader | 輸入流 | 為字符輸入流提供緩沖功能,支持按行讀取,提高讀取效率 |
| BufferedWriter | 輸出流 | 為字符輸出流提供緩沖功能,支持按行寫(xiě)入,提高寫(xiě)入效率 |
| CharArrayReader | 輸入流 | 將字符數(shù)組作為輸入源 |
| CharArrayWriter | 輸出流 | 將數(shù)據(jù)寫(xiě)入到字符數(shù)組 |
| StringReader | 輸入流 | 將字符串作為輸入源 |
| StringWriter | 輸出流 | 將數(shù)據(jù)寫(xiě)入到字符串緩沖區(qū) |
| PrintWriter | 輸出流 | 便捷的字符輸出流,支持自動(dòng)刷新和格式化輸出 |
| PipedReader | 輸入流 | 用于在管道中讀取字符數(shù)據(jù),通常與 PipedWriter 配合使用 |
| PipedWriter | 輸出流 | 用于在管道中寫(xiě)入字符數(shù)據(jù),通常與 PipedReader 配合使用 |
| LineNumberReader | 輸入流 | 帶行號(hào)的緩沖字符輸入流,允許跟蹤讀取的行號(hào) |
| PushbackReader | 輸入流 | 允許在讀取字符后將字符推回流中,以便再次讀取 |
以下是字符流各類(lèi)的讀寫(xiě)文件示例,每個(gè)示例均包含寫(xiě)入和讀取操作:
1. FileReader/FileWriter(文件字符讀寫(xiě))
import java.io.*;
public class Main {
public static void main(String[] args) {
// 寫(xiě)入文本到文件
try (FileWriter writer = new FileWriter("test.txt")) {
writer.write("Hello, FileReader/FileWriter!\n");
writer.write("這是一行行中文文本");
} catch (IOException e) {
e.printStackTrace();
}
// 從文件讀取文本
try (FileReader reader = new FileReader("test.txt")) {
char[] buffer = new char[1024];
int len;
while ((len = reader.read(buffer)) != -1) {
System.out.print(new String(buffer, 0, len));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

2. BufferedReader/BufferedWriter(緩沖字符流)
public class Main {
public static void main(String[] args) {
// 按行寫(xiě)入文本(指定UTF-8編碼)
try (BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream("buffered.txt"), StandardCharsets.UTF_8))) {
writer.write("第一行內(nèi)容");
writer.newLine(); // 跨平臺(tái)換行
writer.write("第二行內(nèi)容");
} catch (IOException e) {
e.printStackTrace();
}
// 按行讀取文本
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(new FileInputStream("buffered.txt"), StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) { // 按行讀取
System.out.println("讀取到:" + line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
3. CharArrayReader/CharArrayWriter(字符數(shù)組流)
CharArrayReader 和 CharArrayWriter 是 Java 中以字符數(shù)組為操作對(duì)象的字符流,所有操作均在內(nèi)存中基于字符數(shù)組完成,無(wú)需依賴(lài)外部存儲(chǔ)。
import java.io.*;
public class CharArrayReadWriteExample {
public static void main(String[] args) {
// CharArrayWriter先寫(xiě)入字符數(shù)組(內(nèi)存中)
CharArrayWriter caw = new CharArrayWriter();
try {
caw.write("先寫(xiě)入內(nèi)存字符數(shù)組,再轉(zhuǎn)存到文件");
char[] charData = caw.toCharArray(); // 獲取字符數(shù)組
// 寫(xiě)入文件
try (FileWriter fw = new FileWriter("charArray.txt")) {
fw.write(charData);
}
// CharArrayReader從字符數(shù)組讀取
CharArrayReader car = new CharArrayReader(charData);
char[] buffer = new char[1024];
int len;
System.out.println("CharArrayReader讀取內(nèi)容:");
while ((len = car.read(buffer)) != -1) {
System.out.print(new String(buffer, 0, len));
}
car.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
caw.close();
}
}
}
4. StringReader/StringWriter(字符串流)
StringReader 和 StringWriter 是 Java 中操作內(nèi)存字符串的字符流,無(wú)需依賴(lài)外部文件,所有操作均在內(nèi)存中完成。
import java.io.*;
public class StringReadWriteExample {
public static void main(String[] args) {
// StringWriter寫(xiě)入字符串緩沖區(qū)
StringWriter sw = new StringWriter();
try {
sw.write("字符串流操作示例\n");
sw.write("數(shù)據(jù)保存在StringBuffer中");
String data = sw.toString(); // 獲取字符串
// 寫(xiě)入文件
try (FileWriter fw = new FileWriter("string.txt")) {
fw.write(data);
}
// StringReader從字符串讀取
StringReader sr = new StringReader(data);
char[] buffer = new char[1024];
int len;
System.out.println("StringReader讀取內(nèi)容:");
while ((len = sr.read(buffer)) != -1) {
System.out.print(new String(buffer, 0, len));
}
sr.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
sw.close();
}
}
}
5. PrintWriter(格式化字符輸出流)
PrintWriter 是 Java 中功能強(qiáng)大的字符輸出流,提供了便捷的文本寫(xiě)入、格式化輸出和自動(dòng)刷新等功能,廣泛用于輸出文本數(shù)據(jù)到文件、控制臺(tái)或其他輸出流。
import java.io.*;
public class PrintWriterExample {
public static void main(String[] args) {
// PrintWriter寫(xiě)入(支持格式化和自動(dòng)刷新)
try (PrintWriter pw = new PrintWriter(new FileWriter("print.txt"), true)) { // 第二個(gè)參數(shù)開(kāi)啟自動(dòng)刷新
pw.println("PrintWriter便捷輸出");
pw.printf("格式化輸出:%d + %d = %d%n", 2, 3, 5); // 類(lèi)似printf格式
pw.println("自動(dòng)刷新生效");
} catch (IOException e) {
e.printStackTrace();
}
// 讀取驗(yàn)證
try (BufferedReader br = new BufferedReader(new FileReader("print.txt"))) {
System.out.println("PrintWriter寫(xiě)入內(nèi)容:");
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
6. PipedReader/PipedWriter(管道字符流,線(xiàn)程間通信)
import java.io.*;
public class PipedReadWriteExample {
public static void main(String[] args) throws IOException {
// 創(chuàng)建管道流對(duì)(必須綁定)
PipedWriter pw = new PipedWriter();
PipedReader pr = new PipedReader(pw);
// 寫(xiě)入線(xiàn)程
Thread writerThread = new Thread(() -> {
try {
pw.write("管道流線(xiàn)程間通信數(shù)據(jù)");
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
});
// 讀取線(xiàn)程(并寫(xiě)入文件)
Thread readerThread = new Thread(() -> {
try (FileWriter fw = new FileWriter("piped.txt")) {
char[] buffer = new char[1024];
int len;
while ((len = pr.read(buffer)) != -1) {
fw.write(buffer, 0, len); // 寫(xiě)入文件
System.out.println("管道讀取內(nèi)容:" + new String(buffer, 0, len));
}
pr.close();
} catch (IOException e) {
e.printStackTrace();
}
});
writerThread.start();
readerThread.start();
}
}
7. LineNumberReader(帶行號(hào)的字符輸入流)
LineNumberReader 是 Java 中帶有行號(hào)跟蹤功能的緩沖字符輸入流,繼承自 BufferedReader,在提供高效緩沖讀取的同時(shí),能自動(dòng)跟蹤當(dāng)前讀取的行號(hào),方便定位文本中的特定行。
import java.io.*;
public class LineNumberReaderExample {
public static void main(String[] args) {
// 先寫(xiě)入多行數(shù)據(jù)
try (BufferedWriter bw = new BufferedWriter(new FileWriter("linenumber.txt"))) {
bw.write("第一行內(nèi)容");
bw.newLine();
bw.write("第二行內(nèi)容");
bw.newLine();
bw.write("第三行內(nèi)容");
} catch (IOException e) {
e.printStackTrace();
}
// LineNumberReader讀取并跟蹤行號(hào)
try (LineNumberReader lnr = new LineNumberReader(new FileReader("linenumber.txt"))) {
lnr.setLineNumber(1); // 設(shè)置起始行號(hào)(默認(rèn)從0開(kāi)始)
String line;
System.out.println("帶行號(hào)的內(nèi)容:");
while ((line = lnr.readLine()) != null) {
System.out.printf("第%d行:%s%n", lnr.getLineNumber(), line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
8. PushbackReader(可回退字符的輸入流)
PushbackReader 是 Java 中的一個(gè)字符輸入流,繼承自 FilterReader,它的特殊之處在于允許將已讀取的字符 “推回”(回退)到流中。
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
PushbackReader reader =new PushbackReader(new FileReader("file.txt"));
int c;
while((c=reader.read())!=-1){
if(c=='o'){
reader.unread(c);
break;
}
System.out.println(":"+(char)c
);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

總結(jié)
到此這篇關(guān)于Java中流(Stream)、文件(File)和IO的文章就介紹到這了,更多相關(guān)Java流(Stream)、文件(File)和IO內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java TCP網(wǎng)絡(luò)通信協(xié)議詳細(xì)講解
TCP/IP是一種面向連接的、可靠的、基于字節(jié)流的傳輸層通信協(xié)議,它會(huì)保證數(shù)據(jù)不丟包、不亂序。TCP全名是Transmission?Control?Protocol,它是位于網(wǎng)絡(luò)OSI模型中的第四層2022-09-09
nodejs連接dubbo服務(wù)的java工程實(shí)現(xiàn)示例
這篇文章主要介紹了在項(xiàng)目遷移中,nodejs連接dubbo服務(wù)的java工程實(shí)現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2022-03-03
SpringBoot?2.x整合Log4j2日志的詳細(xì)步驟
log4j2優(yōu)越的性能其原因在于log4j2使用了LMAX,一個(gè)無(wú)鎖的線(xiàn)程間通信庫(kù)代替了,logback和log4j之前的隊(duì)列,并發(fā)性能大大提升,下面這篇文章主要給大家介紹了關(guān)于SpringBoot?2.x整合Log4j2日志的相關(guān)資料,需要的朋友可以參考下2022-10-10
一文帶你搞懂Java中線(xiàn)程的創(chuàng)建方式
這篇文章主要為大家詳細(xì)介紹了Java中線(xiàn)程的創(chuàng)建方式的相關(guān)知識(shí),文中的示例代碼講解詳細(xì),具有一定的借鑒價(jià)值,感興趣的小伙伴可以了解一下2023-03-03
Java實(shí)現(xiàn)加密傳輸與匿名化的實(shí)戰(zhàn)指南
隨著智慧交通系統(tǒng)的普及,交通數(shù)據(jù)已成為城市大腦的“血液”,然而,這些數(shù)據(jù)中包含的車(chē)牌號(hào)、位置坐標(biāo)、出行時(shí)間等敏感信息,若未妥善保護(hù),可能引發(fā)一系列風(fēng)險(xiǎn),所以本文將通過(guò) Java 實(shí)現(xiàn)加密傳輸與匿名化的實(shí)戰(zhàn),需要的朋友可以參考下2025-09-09
Java中包裝類(lèi)和Arrays類(lèi)的詳細(xì)介紹
Arrays針對(duì)于數(shù)組做操作的類(lèi),該類(lèi)包含用于操作數(shù)組的各種方法(如排序和搜索),這篇文章主要給大家介紹了關(guān)于Java中包裝類(lèi)和Arrays類(lèi)的詳細(xì)介紹,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-12-12

