0

我想要完成的是逐行读取文件并将每一行存储到 ArrayList 中。这应该是一个如此简单的任务,但我一直遇到很多问题。起初,当它被保存回文件时,它正在重复这些行。另一个似乎经常发生的错误是它跳过了尝试但没有捕获异常?我尝试了几种技术,但没有运气。如果您有任何建议或无论如何可以提供帮助,将不胜感激。谢谢

当前代码:

try{
    // command line parameter
    FileInputStream fstream = new FileInputStream(file);
    // Get the object of DataInputStream
    DataInputStream in = new DataInputStream(fstream);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;

    while ((strLine = br.readLine()) != null)   {
        fileList.add(strLine);
    }
    //Close the input stream
    in.close();
} catch (Exception e){//Catch exception if any
    Toast.makeText(this, "Could Not Open File", Toast.LENGTH_SHORT).show();
}
fileList.add(theContent);

//now to save back to the file
try {
    FileWriter writer = new FileWriter(file); 
    for(String str: fileList) { 
        writer.write(str);
        writer.write("\r\n");
    }
    writer.close();
} catch (java.io.IOException error) {
    //do something if an IOException occurs.
    Toast.makeText(this, "Cannot Save Back To A File", Toast.LENGTH_LONG).show();
}
4

2 回答 2

2

有一个非常简单的替代方法可以替代您对类所做的操作Scanner

Scanner s = new Scanner(new File("filepath"));
ArrayList<String> list = new ArrayList<String>();
while (s.hasNext()){
    list.add(s.next());
}
s.close();
于 2012-07-07T20:36:17.370 回答
0

为什么在 try/catch 之后有 fileList.add(theContent) ?我不明白这有什么意义。删除该行,看看它是否有帮助。

例如,我刚刚在我的本地机器上测试了这段代码(不是android,但应该是一样的)

import java.io.*;
import java.util.ArrayList;
class FileRead 
{
 public static void main(String args[])
  {
  ArrayList<String> fileList = new ArrayList<String>();
  final String file = "textfile.txt";
  final String outFile = "textFile1.txt";
  try{
      FileInputStream fstream = new FileInputStream(file);
      DataInputStream in = new DataInputStream(fstream);
      BufferedReader br = new BufferedReader(new InputStreamReader(in));
      String strLine;

      //Read File Line By Line
      while ((strLine = br.readLine()) != null)   {
      // Print the content on the console
        fileList.add(strLine);
      }
      //Close the input stream
      in.close();
    } catch (Exception e){//Catch exception if any
        System.err.println("Error: " + e.getMessage());
    }

   try {
        FileWriter writer = new FileWriter(outFile); 
        for(String str: fileList) { 
          writer.write(str);
          writer.write("\r\n");
        }
        writer.close();
    } catch (java.io.IOException error) {
        System.err.println("Error: " + error.getMessage());
    }
  }
}

在我运行这个之后,这两个文件没有任何区别。所以我的猜测是这条线可能与它有关。

于 2012-07-07T20:37:16.793 回答