如何将.txt文件加载到字符串数组中?
private void FileLoader() {
try {
File file = new File("/some.txt");
Scanner sc = new Scanner(new FileInputStream(file), "Windows-1251");
//Obviously, exception
int i = 0;
while (sc.hasNextLine()) {
morphBuffer[i] = sc.nextLine();
i++;
//Obviously, exception
}
sc.close();
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "File not found: " + e);
return;
}
}
数组的长度有问题,因为我不知道我的数组将有多长。我当然看到了这个问题,但是没有一个字符串数组。我需要它,因为我必须处理整个文本以及 null
字符串。如何将文本文件加载到字符串数组中?
从Java 7开始,您可以在一行代码中完成此操作:
List<String> allLines = Files.readAllLines("/some.txt", Charset.forName("Cp1251"));
如果您需要数据使用字符串数组而不是List<String>
,请调用方法toArray(new Strinf[0])
的结果readAllLines
:
String[] allLines = Files.readAllLines("/some.txt", Charset.forName("Cp1251")).toArray(new String[0]);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句