我创建了以下代码以将文件内容显示到文本区域 - 并且成功了:
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("C:\\Users\\emily\\Documents\\Parts.txt"));
String str;
while ((str = in.readLine()) != null) {
jTextArea1.append("\n"+str);
}
} catch (IOException e) {
} finally {
try { in.close(); } catch (Exception ex) { }
}
我的问题是我需要数组中的每一行。我的概念证明的想法是我能够输入命令:
jTextArea1 = Arrays.toString(fileArray);
尽管我在互联网上进行了搜索,但我似乎无法完成此任务。谁能告诉我如何将这些值加载到数组(fileArray)中,而不是将它们写入 jTextArea 中?
最佳答案
较新的类 Path 和 Files 就可以了。
Path path = Paths.get("C:\\Users\\emily\\Documents\\Parts.txt");
try {
List<String> lines = Files.readAllLines(path, Charset.defaultCharset());
String[] array = lines.toArray(new String[lines.size()]);
...
} catch (IOException e) {
//Logger.getLogger(getClass().getName()).log(Level.SEVERE,
// path.toString(), e);
System.err.println("Could not read file: " + e.getMessage());
}
最好是只使用列表。
<小时/>添加对可能的 IOException 的处理,可能是在无法读取文件时。
关于java - 文件到数组 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34029234/