将文本文件存储到数组中,反之亦然

时间:2016-06-27 10:04:10

标签: java arrays text-files

我正在尝试将文本文件读入数组,修改数组,然后将其存储回文本文件以备将来使用。

数组只有一列宽,所以我希望文本文件的每一行都存储在每个数组元素中。

我是在一个大项目的中间做这个,所以我之前找到的相关答案似乎不适合。

这是我的代码:

listeventfuture

我的变量声明都没问题,因为我现在只遇到运行时错误。请告诉我代码中的任何错误 - 提前感谢: - )

1 个答案:

答案 0 :(得分:1)

首先,使用数组作为文件的内部数据结构是没有意义的。因为您不知道预先读了多少行。使用List<String>ArrayList作为实现时,LinkedList就足够了。

第二:不要使用原始Reader而是BufferedReader。使用此BufferedReader,您可以使用方法readLine()逐行读取文件。同样,您可以使用PrintWriter逐行写入文件。

第三:您应该使用显式字符编码。不要依赖标准编码,因为不同操作系统的标准编码可能不同(例如Windows-ANSI aka Cp1252 for Windows和UTF-8 for Linux)。

第四:使用try-with-resources语句打开输入和输出流。因此,您更容易确保在每种情况下都关闭它们。

我假设context.openFileInput("readList1.txt")的返回类型是'InputStream`,字符编码是UTF-8:

List<String> readList = new ArrayList<String>();
// Read the file line by line into readList
try(
  BufferedReader reader = new BufferedReader(new InputStreamReader(
      context.openFileInput("readList1.txt"), "UTF-8"));
) {
  String line;
  while((line = reader.readLine()) != null) {
    readList.add(line);
  } 
} catch(IOException ioe) {
  ioe.printStackTrace();
}

// Modify readList
// ...

// Write readList line by line to the file
try(
  PrintWriter writer = new PrintWriter(new OutputStreamWriter(
    context.openFileOutput("readList1.txt", context.MODE_WORLD_READABLE), "UTF-8")));
) {
  for(String line: readList) {
    writer.println(line); 
  }
  writer.flush();
} catch (IOException ioe) {
  ioe.printStackTrace();
}