使用 Java 中的 Files.readAllLines 方法将 TXT 文件的内容读取到列表中,然后使用 toArray 方法将列表的内容复制到字符串数组中即可将 TXT 文件存储到数组中。

Java 中将 TXT 文件存储到数组的方法
将 TXT 文件中的内容存储到 Java 数组中是一种常见的操作。以下是对实现此操作的逐步指南:
1. 导入必要的类
<code class="java">import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.ArrayList; import java.util.List;</code>
2. 创建一个文件对象
立即学习“Java免费学习笔记(深入)”;
<code class="java">File file = new File("path/to/text_file.txt");</code>3. 读取文件内容到列表
使用 Files.readAllLines 方法读取文件内容并将其存储在列表中。
<code class="java">List<String> lines = null;
try {
lines = Files.readAllLines(file.toPath());
} catch (IOException e) {
e.printStackTrace();
}</code>4. 创建一个数组来存储列表内容
根据列表的大小创建一个字符串数组。
<code class="java">String[] array = new String[lines.size()];</code>
5. 将列表内容复制到数组
使用 toArray 方法将列表的内容复制到数组中。
<code class="java">array = lines.toArray(array);</code>
示例代码:
<code class="java">import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
public class TxtToArray {
public static void main(String[] args) {
// 文件路径
String filePath = "path/to/text_file.txt";
// 创建 File 对象
File file = new File(filePath);
// 读取文件到列表
List<String> lines = null;
try {
lines = Files.readAllLines(file.toPath());
} catch (IOException e) {
e.printStackTrace();
}
// 创建数组来存储列表内容
String[] array = new String[lines.size()];
// 将列表内容复制到数组
array = lines.toArray(array);
// 输出数组内容
for (String line : array) {
System.out.println(line);
}
}
}</code>注意:
IOException。以上就是java怎么把txt存入数组的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号