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



我试图将文本文件读取到数组中,修改数组,然后将其存储回文本文件以备将来使用。

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

我在一个大程序中间这样做,所以我以前发现的相关答案似乎不适合。

这是我的代码:

checkReadHeader = parts[0];
if (checkReadHeader.equals("LETSDOIT"))
{
    readMsg = parts[1];
    readj = 0;
    if(readMsg.equals(logging1)){
        //---------------------------------------
        // READ readlist1.txt AND STORE IT INTO STRING ARRAY readlist
        //---------------------------------------
        try
        {
            fIn = context.openFileInput("readList1.txt");
            isr = new InputStreamReader(fIn);
            while ((charRead = isr.read(inputBuffer)) > 0)
            {
                String readString = String.copyValueOf(inputBuffer, 0, charRead);
                if(!readString.equals("n"))
                {
                    readList[readj][0] += readString;
                }
                else
                {
                    readj += 1;
                }         
                inputBuffer = new char[100];
            }
        }
        catch (IOException ioe)
        {
            ioe.printStackTrace();
        }
    }
    //---------------------------------------
    // MODIFY readlist
    //---------------------------------------
    readList[j][0] = testdate;
    //---------------------------------------
    // STORE readlist BACK INTO TEXT FILE readlist1.txt
    //---------------------------------------
    try
    {
        fOut = context.openFileOutput("readList1.txt", context.MODE_WORLD_READABLE);
        osw = new OutputStreamWriter(fOut);
        osw.write(readList.toString());
        osw.flush();
        osw.close();
    }
    catch (IOException ioe)
    {
        ioe.printStackTrace();
    }
}

我的变量声明都可以,因为我现在只遇到一个运行时错误。请告知我我的代码中的任何错误 - 预先感谢: - )

第一个,将数组用作文件的内部数据结构是没有意义的。因为您不知道会事先阅读多少行。用ArrayListLinkedList作为实现,List<String>更加足够。

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

第三:您应该使用明确的字符编码。不要依靠标准编码,因为对于不同的操作系统,标准编码可能会有所不同(例如,Windows-ansi aka aka cp1252用于Windows,而Linux的UTF-8)。

第四:使用try-with-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();
}

最新更新