Java文件讀寫與異常處理從入門到實戰(zhàn)指南
在Java編程中,文件輸入輸出和異常處理是兩個緊密相連的核心技能。無論是讀取配置文件、寫入日志,還是處理用戶上傳的數(shù)據(jù),都離不開對文件的操作。而文件操作中又充滿了各種不確定性(文件不存在、權(quán)限不足、IO錯誤等),這就離不開異常處理機制。
本文將結(jié)合Java標(biāo)準(zhǔn)庫中的File、Scanner、PrintWriter等類,系統(tǒng)講解如何安全、優(yōu)雅地進(jìn)行文本文件的讀寫,并結(jié)合異常處理機制,讓程序更加健壯。
一、File類:文件與目錄的抽象
File類是java.io包中代表文件或目錄路徑的對象,它并不操作文件內(nèi)容,而是用來:
- 獲取文件屬性(大小、路徑、是否可讀寫)
- 創(chuàng)建、刪除、重命名文件或目錄
- 判斷文件是否存在、是否為目錄等
示例:創(chuàng)建File對象
// Windows風(fēng)格(注意轉(zhuǎn)義)
File file1 = new File("D:\\temp\\test.txt");
// Unix風(fēng)格(推薦)
File file2 = new File("D:/temp/test.txt");
// 分目錄和文件名
File dir = new File("D:/myDir");
File file3 = new File(dir, "data.txt");常用方法
| 方法 | 說明 |
|---|---|
getName() | 獲取文件名 |
getAbsolutePath() | 獲取絕對路徑 |
exists() | 判斷是否存在 |
isFile() / isDirectory() | 判斷是文件還是目錄 |
length() | 獲取文件大?。ㄗ止?jié)) |
二、讀文件:Scanner + File
Java 提供了 Scanner 類,不僅可以讀取控制臺輸入,也可以讀取文件。
步驟
- 創(chuàng)建
File對象 - 將
File對象傳給Scanner構(gòu)造器 - 使用
nextLine()、nextInt()等方法讀取 - 關(guān)閉
Scanner
示例:讀取文本文件
import java.io.*;
import java.util.Scanner;
public class ReadFileDemo {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("names.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
}
}??
Scanner構(gòu)造器會拋出FileNotFoundException,必須處理或聲明。
三、寫文件:PrintWriter + FileWriter
PrintWriter 類提供了 print() 和 println() 方法,非常適合寫文本文件。
基本寫法(覆蓋模式)
PrintWriter out = new PrintWriter("output.txt");
out.println("Hello, Java!");
out.println("File writing test.");
out.close();
追加模式
如果不想覆蓋原有內(nèi)容,可以使用 FileWriter 的追加構(gòu)造器:
FileWriter fw = new FileWriter("output.txt", true);
PrintWriter out = new PrintWriter(fw);
out.println("這行會被追加到文件末尾");
out.close();
注意:
PrintWriter也會拋出IOException,方法簽名中需要throws IOException。
四、異常處理:讓程序更安全
文件操作中常見的異常包括:
FileNotFoundException:文件不存在IOException:讀寫錯誤NumberFormatException:數(shù)據(jù)格式錯誤
使用 try-catch 捕獲異常
try {
File file = new File("data.txt");
Scanner sc = new Scanner(file);
while (sc.hasNext()) {
System.out.println(sc.nextLine());
}
sc.close();
} catch (FileNotFoundException e) {
System.out.println("文件未找到:" + e.getMessage());
}
多異常處理
try {
// 可能拋出多種異常的代碼
} catch (FileNotFoundException e) {
System.out.println("文件不存在");
} catch (IOException e) {
System.out.println("IO錯誤");
}
? 子類異常必須寫在父類異常之前
finally 子句:無論如何都會執(zhí)行
Scanner sc = null;
try {
sc = new Scanner(new File("test.txt"));
// 讀取文件
} catch (FileNotFoundException e) {
System.out.println("文件未找到");
} finally {
if (sc != null) {
sc.close(); // 保證資源被釋放
}
}
五、拋出異常:throws 與 throw
throws:聲明方法可能拋出異常
public void readFile(String path) throws FileNotFoundException {
Scanner sc = new Scanner(new File(path));
// ...
}
throw:手動拋出異常
if (amount < 0) {
throw new IllegalArgumentException("金額不能為負(fù)數(shù)");
}
自定義異常類
class NegativeBalanceException extends Exception {
public NegativeBalanceException(String msg) {
super(msg);
}
}
六、Checked vs Unchecked 異常
| 類型 | 父類 | 是否必須處理 | 常見例子 |
|---|---|---|---|
| Checked | Exception(非RuntimeException) | 是 | IOException, FileNotFoundException |
| Unchecked | RuntimeException / Error | 否 | NullPointerException, ArithmeticException |
文件操作中的異常大多是 Checked Exception,必須處理或聲明拋出。
七、實戰(zhàn):完整的文件復(fù)制程序
import java.io.*;
public class FileCopy {
public static void main(String[] args) {
String src = "source.txt";
String dest = "dest.txt";
try (BufferedReader reader = new BufferedReader(new FileReader(src));
PrintWriter writer = new PrintWriter(new FileWriter(dest))) {
String line;
while ((line = reader.readLine()) != null) {
writer.println(line);
}
System.out.println("復(fù)制成功");
} catch (FileNotFoundException e) {
System.out.println("源文件不存在");
} catch (IOException e) {
System.out.println("IO錯誤:" + e.getMessage());
}
}
}? 這里使用了 try-with-resources(Java 7+),自動關(guān)閉資源,更加簡潔安全。
總結(jié)
File類操作文件路徑和屬性Scanner+File讀文本文件PrintWriter+FileWriter寫文本文件- 文件操作必須處理
IOException等 checked 異常 - 使用
try-catch-finally或try-with-resources保證資源釋放 - 區(qū)分 checked 和 unchecked 異常,合理設(shè)計異常處理策略
掌握文件讀寫與異常處理,是走向Java實戰(zhàn)開發(fā)的重要一步。希望這篇文章能幫助你寫出更穩(wěn)健、更專業(yè)的Java代碼。
到此這篇關(guān)于Java文件讀寫與異常處理從入門到實戰(zhàn)指南的文章就介紹到這了,更多相關(guān)Java文件讀寫與異常處理內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
關(guān)于通過java調(diào)用datax,返回任務(wù)執(zhí)行的方法
今天小編就為大家分享一篇關(guān)于通過java調(diào)用datax,返回任務(wù)執(zhí)行的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08
springboot中使用redis并且執(zhí)行調(diào)試lua腳本
今天有個項目需要使用redis,并且有使用腳本的需求,本文主要介紹了springboot中使用redis并且執(zhí)行調(diào)試lua腳本,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-04-04
java使用BeanUtils.copyProperties踩坑經(jīng)歷
最近在做個項目,踩了個坑特此記錄一下,本文主要介紹了使用BeanUtils.copyProperties踩坑經(jīng)歷,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05
淺談Java并發(fā)編程之synchronized有序性誤區(qū)
本文主要介紹了淺談Java并發(fā)編程之synchronized有序性誤區(qū),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2026-02-02
Spring攔截器HandlerInterceptor接口代碼解析
這篇文章主要介紹了Spring攔截器HandlerInterceptor接口代碼解析,具有一定借鑒價值,需要的朋友可以參考下2017-12-12

