Java如何将文本文件中的单词存储到String数组中
实现方案
你已经提前定义了固定长度的目标数组,直接按行读取txt文件逐行填充即可,以下是两种可直接运行的实现,注意处理IO资源释放、文件编码问题即可。
前置注意点
- 路径里的空格、方括号不需要额外转义,Java文件API可以正常识别该路径
- 建议显式指定文件编码,避免系统默认编码导致的乱码问题,英文词表通用编码为UTF-8
- 读取时建议对每行内容做
trim()处理,剔除词表中可能存在的首尾多余空格、隐藏制表符
Java 8+ 简洁实现(推荐)
用JDK内置的NIO接口可以一次性读取所有行,不需要手动维护循环和流关闭:
import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.io.IOException; public class LoadWordList { public static void main(String[] args) { String[] words = new String[82094]; String targetPath = "F:/Word Game/Words List [UK ENGLISH].txt"; try { words = Files.readAllLines(Paths.get(targetPath), StandardCharsets.UTF_8) .toArray(new String[0]); } catch (IOException e) { // 可替换为自定义的异常处理逻辑,比如弹窗提示文件不存在 e.printStackTrace(); } // 测试:打印前5个单词验证读取结果 for (int i = 0; i < 5; i++) { System.out.println(words[i]); } } }
兼容旧JDK版本的实现(JDK7及以下)
如果你的开发环境不支持Java 8新特性,用BufferedReader逐行读取手动填充数组即可:
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class LoadWordList { public static void main(String[] args) { String[] words = new String[82094]; String targetPath = "F:/Word Game/Words List [UK ENGLISH].txt"; BufferedReader br = null; int currentIndex = 0; try { br = new BufferedReader(new FileReader(targetPath)); String lineContent; // 逐行读取,直到读完文件或填满数组 while ((lineContent = br.readLine()) != null && currentIndex < words.length) { words[currentIndex] = lineContent.trim(); currentIndex++; } } catch (IOException e) { e.printStackTrace(); } finally { // 必须手动关闭IO资源,避免资源占用 if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
优化建议
- 不需要提前手动统计文件行数定义固定长度数组,用
ArrayList<String>动态存储单词更灵活,后续词表增删单词不需要修改代码,需要数组时调用toArray(new String[0])即可转换 - 如果读取后数组长度不符合预期,先检查文件末尾是否存在自动生成的空行,这类空行会被识别为有效内容占用数组位置
内容的提问来源于stack exchange,提问作者Aabir Bhattacharya
相关产品推荐
相关产品推荐

