2010-05-25 28 views
59

Tôi mới phát triển Android.Làm cách nào để đọc tệp văn bản từ thẻ SD trong Android?

Tôi cần đọc tệp văn bản từ thẻ SD và hiển thị tệp văn bản đó. Có cách nào để xem tệp văn bản trực tiếp trong Android hay cách khác làm cách nào tôi có thể đọc và hiển thị nội dung của tệp văn bản?

+0

bạn có muốn biết làm thế nào để viết một chương trình mà đọc một file txt hoặc bạn có muốn biết làm thế nào để làm nó như một người sử dụng? – SteelBytes

Trả lời

120

In your layout bạn sẽ cần thứ gì đó để hiển thị văn bản. A TextView là sự lựa chọn hiển nhiên. Vì vậy, bạn sẽ có một cái gì đó như thế này:

<TextView 
    android:id="@+id/text_view" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"/> 

Và mã của bạn sẽ trông như thế này:

//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'); 
    } 
    br.close(); 
} 
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); 

Điều này có thể đi vào các phương pháp onCreate() của Activity của bạn, hoặc ở một nơi khác tùy thuộc vào chỉ là những gì nó là bạn muốn làm.

+0

Không hoạt động, nó trả về văn bản là null –

+1

@Android Developer - Trong mã mẫu, thông báo "Bạn sẽ cần thêm xử lý lỗi thích hợp tại đây". Bạn đã làm điều đó bởi vì đó có thể là nơi hầu như giống như bạn sẽ tìm thấy vấn đề của bạn. –

+0

@Dave Webb xin lỗi vì đã không cập nhật nhận xét của tôi. nó cũng làm việc cho tôi. Trên thực tế khi tôi đặt các tập tin trong DDMS sau đó nó sẽ xóa tất cả các dữ liệu từ tập tin thats tại sao nó trả về null ở cuối của tôi. –

5

Để đối phó với

Đừng hardcode/sdcard/

Đôi khi chúng ta CÓ PHẢI hardcode nó như trong một số mẫu điện thoại là phương pháp API trả về bộ nhớ điện thoại nội bộ.

Các loại đã biết: HTC One X và Samsung S3.

Environment.getExternalStorageDirectory().getAbsolutePath() gives a different path - Android

+0

cho tôi nó cung cấp cho một số tài liệu bảo mật agumentation rác /com.app.name/data/sdcard/ ... được nhận thức. cho các bản ghi cho bản thân mình tôi mã cứng nó cuối cùng nó hoạt động. –

0
package com.example.readfilefromexternalresource; 

import java.io.BufferedReader; 
import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.FileReader; 
import java.io.IOException; 

import android.app.Activity; 
import android.app.ActionBar; 
import android.app.Fragment; 
import android.os.Bundle; 
import android.os.Environment; 
import android.view.LayoutInflater; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.TextView; 
import android.widget.Toast; 
import android.os.Build; 

public class MainActivity extends Activity { 
    private TextView textView; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     // TODO Auto-generated method stub 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     textView = (TextView)findViewById(R.id.textView); 
     String state = Environment.getExternalStorageState(); 

     if (!(state.equals(Environment.MEDIA_MOUNTED))) { 
      Toast.makeText(this, "There is no any sd card", Toast.LENGTH_LONG).show(); 


     } else { 
      BufferedReader reader = null; 
      try { 
       Toast.makeText(this, "Sd card available", Toast.LENGTH_LONG).show(); 
       File file = Environment.getExternalStorageDirectory(); 
       File textFile = new File(file.getAbsolutePath()+File.separator + "chapter.xml"); 
       reader = new BufferedReader(new FileReader(textFile)); 
       StringBuilder textBuilder = new StringBuilder(); 
       String line; 
       while((line = reader.readLine()) != null) { 
        textBuilder.append(line); 
        textBuilder.append("\n"); 

       } 
       textView.setText(textBuilder); 

      } catch (FileNotFoundException e) { 
       // TODO: handle exception 
       e.printStackTrace(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
      finally{ 
       if(reader != null){ 
        try { 
         reader.close(); 
        } catch (IOException e) { 
         // TODO Auto-generated catch block 
         e.printStackTrace(); 
        } 
       } 
      } 

     } 
    } 
} 
1
BufferedReader br = null; 
try { 
     String fpath = Environment.getExternalStorageDirectory() + <your file name>; 
     try { 
      br = new BufferedReader(new FileReader(fpath)); 
     } catch (FileNotFoundException e1) { 
      e1.printStackTrace(); 
     } 
     String line = ""; 
     while ((line = br.readLine()) != null) { 
     //Do something here 
     } 
+0

Bạn có thể cung cấp lời giải thích cho mã của bạn không ... như ở đâu để sử dụng nó, tại sao điều đó lại thực hiện công việc, v.v. – Soma

0

Cẩn thận: một số điện thoại có 2 sdcards, một cố định một và một card rời nội bộ. Bạn có thể tìm thấy tên cuối cùng qua ứng dụng chuẩn: "Mijn Bestanden" (bằng tiếng Anh: "MyFiles"?) Khi tôi mở ứng dụng này (mục: tất cả các tệp) đường dẫn của thư mục mở là "/ sdcard ", cuộn xuống có một mục" bên ngoài-sd ", nhấp vào đây sẽ mở thư mục"/sdcard/external_sd/". Giả sử tôi muốn mở một tập tin văn bản "MyBooks.txt" Tôi sẽ sử dụng một cái gì đó như:

String Filename = "/mnt/sdcard/external_sd/MyBooks.txt" ; 
    File file = new File(fname);...etc... 
Các vấn đề liên quan