Java读取与写入TXT文件的高效方法详解与实践案例

2026-01-08 18:13:40

引言

在Java编程中,文件处理是一项基本且重要的技能。无论是读取数据进行分析,还是将结果写入文件保存,掌握高效的文件读写方法都能大大提升开发效率。本文将详细介绍Java中读取和写入TXT文件的方法,并通过实际案例展示如何应用这些技术。

一、读取TXT文件

1.1 使用BufferedReader

BufferedReader是Java中读取文本文件最常用的类之一,它提供了缓冲功能,可以高效地逐行读取文件内容。

示例代码:

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;

public class ReadTxtFile {

public static void main(String[] args) {

String filePath = "path/to/your/file.txt";

try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {

String line;

while ((line = br.readLine()) != null) {

System.out.println(line);

}

} catch (IOException e) {

e.printStackTrace();

}

}

}

1.2 使用Scanner

Scanner类同样可以用于读取文本文件,特别适合需要逐行处理的场景。

示例代码:

import java.io.File;

import java.io.FileNotFoundException;

import java.util.Scanner;

public class ReadTxtWithScanner {

public static void main(String[] args) {

String filePath = "path/to/your/file.txt";

try (Scanner scanner = new Scanner(new File(filePath))) {

while (scanner.hasNextLine()) {

String line = scanner.nextLine();

System.out.println(line);

}

} catch (FileNotFoundException e) {

e.printStackTrace();

}

}

}

二、写入TXT文件

2.1 使用FileWriter

FileWriter类用于写入字符文件,可以方便地追加或覆盖文件内容。

示例代码:

import java.io.FileWriter;

import java.io.IOException;

public class WriteTxtFile {

public static void main(String[] args) {

String filePath = "path/to/your/file.txt";

try (FileWriter fw = new FileWriter(filePath, true)) { // true表示追加写入

fw.write("Hello, World!\n");

fw.write("This is a new line.\n");

} catch (IOException e) {

e.printStackTrace();

}

}

}

2.2 使用BufferedWriter

BufferedWriter提供了缓冲功能,可以更高效地写入文件。

示例代码:

import java.io.BufferedWriter;

import java.io.FileWriter;

import java.io.IOException;

public class WriteTxtWithBufferedWriter {

public static void main(String[] args) {

String filePath = "path/to/your/file.txt";

try (BufferedWriter bw = new BufferedWriter(new FileWriter(filePath, true))) {

bw.write("Hello, BufferedWriter!\n");

bw.write("This is another new line.\n");

} catch (IOException e) {

e.printStackTrace();

}

}

}

三、综合案例:文件复制

下面是一个综合案例,展示如何将一个TXT文件的内容复制到另一个文件中。

示例代码:

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;

public class CopyTxtFile {

public static void main(String[] args) {

String sourceFilePath = "path/to/source/file.txt";

String targetFilePath = "path/to/target/file.txt";

try (BufferedReader br = new BufferedReader(new FileReader(sourceFilePath));

BufferedWriter bw = new BufferedWriter(new FileWriter(targetFilePath))) {

String line;

while ((line = br.readLine()) != null) {

bw.write(line);

bw.newLine(); // 添加换行符

}

} catch (IOException e) {

e.printStackTrace();

}

}

}

四、远程HTTPS文件读取

在实际应用中,有时需要从远程HTTPS地址读取文件。可以使用URL类和InputStream来实现。

示例代码:

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.net.URL;

import java.security.cert.X509Certificate;

import java.security.cert.CertificateException;

import javax.net.ssl.HttpsURLConnection;

import javax.net.ssl.SSLContext;

import javax.net.ssl.TrustManager;

import javax.net.ssl.X509TrustManager;

public class ReadRemoteHttpsFile {

public static void main(String[] args) {

String httpsUrl = "https://example.com/file.txt";

// 忽略SSL证书验证(不推荐在生产环境中使用)

TrustManager[] trustAllCerts = new TrustManager[]{

new X509TrustManager() {

public X509Certificate[] getAcceptedIssuers() { return null; }

public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {}

public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {}

}

};

try {

SSLContext sc = SSLContext.getInstance("SSL");

sc.init(null, trustAllCerts, new java.security.SecureRandom());

HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

URL url = new URL(httpsUrl);

HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

connection.setRequestMethod("GET");

try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {

String line;

while ((line = br.readLine()) != null) {

System.out.println(line);

}

}

} catch (Exception e) {

e.printStackTrace();

}

}

}

五、总结

本文详细介绍了Java中读取和写入TXT文件的方法,并通过实际案例展示了如何应用这些技术。无论是处理本地文件还是远程HTTPS文件,掌握这些方法都能让你的Java编程更加高效。希望本文能对你有所帮助,在实际项目中灵活运用这些技巧,提升开发效率。