Java读取TXT文件并存入数组的方法
在Java中读取TXT文件并将其内容存入数组有多种方法,以下是几种常见的实现方式:

方法1:使用BufferedReader逐行读取
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class ReadTxtToArray {
public static void main(String[] args) {
String filePath = "example.txt"; // 替换为你的文件路径
ArrayList<String> lines = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = br.readLine()) != null) {
lines.add(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// 将ArrayList转换为数组(如果需要)
String[] array = lines.toArray(new String[0]);
// 打印数组内容
for (String str : array) {
System.out.println(str);
}
}
}
方法2:使用Files类(Java 7+)
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
public class ReadTxtToArray {
public static void main(String[] args) {
String filePath = "example.txt"; // 替换为你的文件路径
try {
// 读取所有行到List
String[] lines = Files.readAllLines(Paths.get(filePath))
.toArray(new String[0]);
// 打印数组内容
Arrays.stream(lines).forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
}
方法3:读取数值数据到数组
如果TXT文件包含数值数据(如每行一个数字):
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class ReadNumbersToArray {
public static void main(String[] args) {
String filePath = "numbers.txt"; // 替换为你的文件路径
ArrayList<Integer> numbers = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = br.readLine()) != null) {
numbers.add(Integer.parseInt(line.trim()));
}
} catch (IOException | NumberFormatException e) {
e.printStackTrace();
}
// 转换为int数组
int[] array = numbers.stream().mapToInt(i -> i).toArray();
// 打印数组内容
for (int num : array) {
System.out.println(num);
}
}
}
注意事项
- 文件路径:确保文件路径正确,可以使用绝对路径或相对路径
- 异常处理:文件操作可能抛出IOException,需要适当处理
- 内存考虑:对于大文件,逐行读取(方法1)比一次性读取(方法2)更节省内存
- 编码问题:如果文件使用非UTF-8编码,需要指定字符集:
new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "GBK"))
选择哪种方法取决于你的具体需求,如文件大小、数据类型和性能要求。

