2011-01-11 26 views
2

私はちょうど電話のメモリにテキストファイルを作成し、その内容を表示する必要があります。私はテキストファイルを作成しました。しかし、data/data/package-名前/ファイル名.txt &エミュレータの内容が表示されませんでした。アンドロイドの電話メモリからテキストファイルを読み込みます

私のコードは..ですADVで

public class PhonememAct extends Activity { 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     TextView tv=(TextView)findViewById(R.id.tv); 

     FileOutputStream fos = null; 
     try { 
      fos = openFileOutput("Test.txt", Context.MODE_PRIVATE); 
     } catch (FileNotFoundException e2) { 
      // TODO Auto-generated catch block 
      e2.printStackTrace(); 
     } 
     try { 
      fos.write("Hai..".getBytes()); 
     } catch (IOException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } 
     try { 
      fos.close(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 


     FileInputStream fis = null; 
     try { 
      fis = openFileInput("Test.txt"); 
     } catch (FileNotFoundException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     int c; 

     try { 
      while((c=fis.read())!=-1) 
        { 
         tv.setText(c); 
         setContentView(tv); 

         //k += (char)c; 
        } 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

      try { 
       fis.close(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 


    } 
} 

感謝。

+0

また、1つのtryブロックを入れて、さまざまな例外をキャッチすることができます。これはコードをより読みやすくします;) – Beasly

答えて

6

単純にテキストの書き込み/読み取りを行う場合は、入力/出力ストリームを使用する必要はありません。

FileWriterを使用してファイルにテキストを書き込み、BufferedReaderを使用してファイルからテキストを読み取ります。これははるかに簡単です。これは完璧に動作...

try { 
    File myDir = new File(getFilesDir().getAbsolutePath()); 
    String s = ""; 

    FileWriter fw = new FileWriter(myDir + "/Test.txt"); 
    fw.write("Hello World"); 
    fw.close(); 

    BufferedReader br = new BufferedReader(new FileReader(myDir + "/Test.txt")); 
    s = br.readLine(); 

    // Set TextView text here using tv.setText(s); 

} catch (FileNotFoundException e) { 
    e.printStackTrace(); 
} catch (IOException e) { 
    e.printStackTrace(); 

}

+0

私はあなたのexample.Textファイルを試してみましたwell.But私はプログラムを実行しようとしたときに、私は "プロセスが予期せず停止"私のlogcatは.01-11 14:24:05.253:ERROR/AndroidRuntime(25814):キャッチされていないハンドラ:キャッチされていない例外のためにメインスレッドが終了する 01-11 14:24:05.263:ERROR/AndroidRuntime(25814): – sanjay

+0

@ Sudhakar:私はあなたが "setContentView(tv);"そうですね。 TextViewを含むmain.xmlなどのXMLレイアウトファイルが必要です。また、「setContentView(R.layout.main);」を呼び出す必要があります。あなたが "super.onCreate(savedInstanceState)"を呼び出した直後です。コンテンツビューを 'tv'に設定しないでください。 – Squonk

+0

素晴らしい!最後に私は持っています.Squonkさん、ありがとうございます。 – sanjay

0

これはあなたの質問に対する回答ではありません。
私は、try-catchを正しく使用する必要があると思います。 openFileInput()呼び出しが失敗し、次にヌルオブジェクトでfos.write()fos.close()を呼び出していると想像してください。

fis.read()fis.close()で後で同じことが見られます。

1つのtry-catchブロックにopenFileInput(),fos.write()およびfos.close()を含める必要があります。同様の変更は 'fis'にも必要です。

これを最初にお試しください!

+0

返事ありがとうございます。私はしようとします.. – sanjay

0

ストリームで試すことができます。

public static void persistAll(Context ctx, List<myObject> myObjects) { 

    // save data to file 
    FileOutputStream out = null; 

    try { 
      out = ctx.openFileOutput("file.obj", 

      Context.MODE_PRIVATE); 
      ObjectOutputStream objOut = new ObjectOutputStream(out); 
      objOut.writeObject(myObjects); 
      } catch (Exception e) { 
     e.printStackTrace(); 
      } finally { 
      try { 
       out.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 

それはこのように私のために正常に動作しています。テキストとして保存するのはそれほど違うはずはありませんが、ここでは仕事場でテストするためのJava IDEはありません。 これが役立つことを願っています!

1
//Find the directory for the SD Card using the API 
    //*Don't* hardcode "/sdcard" 
    File sdcard = Environment.getExternalStorageDirectory(); 

    //Get the text file 
    File file = new File(sdcard,"file.txt"); 

    //Read text from file 
    StringBuilder text = new StringBuilder(); 

    try { 
    BufferedReader br = new BufferedReader(new FileReader(file)); 
    String line; 

    while ((line = br.readLine()) != null) { 
    text.append(line); 
    text.append('\n'); 
    } 
    } 
    catch (IOException e) { 
    //You'll need to add proper error handling here 
    } 

    //Find the view by its id 
    TextView tv = (TextView)findViewById(R.id.text_view); 

    //Set the text 
    tv.setText(text); 
1
//To read file from internal phone memory 
//get your application context: 
Context context = getApplicationContext(); 

filePath = context.getFilesDir().getAbsolutePath(); 
File file = new File(filePath, fileName); 
StringBuilder text = new StringBuilder(); 

try { 
    BufferedReader br = new BufferedReader(new FileReader(file)); 
    while ((line = br.readLine()) != null) { 
     text.append(line); 
     text.append('\n'); 
    } 
} 
catch (IOException e) { 

} 
return text.toString(); //the output text from file.