0

私が達成しようとしているのは、ファイルを 1 行ずつ読み取り、各行を ArrayList に格納することです。これはとても簡単な作業のはずですが、私は多くの問題に直面しています。最初は、ファイルに保存されたときに行を繰り返していました。かなり頻繁に発生するように思われる別のエラーは、try をスキップするが例外をキャッチしないというものですか? いくつかのテクニックを試しましたが、うまくいきません。何かアドバイスがあれば、またはとにかく助けていただければ幸いです。ありがとうございました

現在のコード:

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());
    }
  }
}

これを実行した後、2つのファイルに違いはありませんでした。だから私の推測では、その線はそれと関係があるかもしれません。

于 2012-07-07T20:37:16.793 に答える