2012-05-11 24 views
5

Tôi mới phát triển Android và tôi cần bạn trợ giúp. Tôi đã được khóa tại các chủ đề tương tự cho sự phát triển của tôi nhưng không giúp tôi. Cho đến nay tôi tạo ra các chức năng giúp tôi lấy các tập tin từ sdcard của mình và hiển thị cho tôi danh sách sau đó. Đó là làm việcCách đọc tệp văn bản đã chọn từ sdcard trên android

đây là đoạn code để nhận được đường dẫn trên sdcard:

package com.seminarskirad; 

import android.app.AlertDialog; 
import android.app.AlertDialog.Builder; 
import android.app.ListActivity; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.net.Uri; 
import android.os.Bundle; 
import android.os.Environment; 
import android.provider.MediaStore; 
import android.util.Log; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.ArrayAdapter; 
import android.widget.ListView; 
import android.widget.TextView; 

import java.io.BufferedReader; 
import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.FileReader; 
import java.io.FilenameFilter; 
import java.io.IOException; 
import java.net.URISyntaxException; 
import java.util.ArrayList; 
import java.util.List; 

public class LoadActivity extends ListActivity{ 

    private enum DISPLAYMODE{ ABSOLUTE, RELATIVE; } 
    private final DISPLAYMODE displayMode = DISPLAYMODE.ABSOLUTE; 
    private List<String> directoryEntries = new ArrayList<String>(); 
    private File currentDirectory = new File("/"); 

     @Override 
     public void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      Browse(Environment.getExternalStorageDirectory()); 

     } 

     private void upOneLevel(){ 
       if(this.currentDirectory.getParent() != null) 
         this.Browse(this.currentDirectory.getParentFile()); 
     } 

     private void Browse(final File aDirectory){ 
       if (aDirectory.isDirectory()){ 
         this.currentDirectory = aDirectory; 
         fill(aDirectory.listFiles()); 

       } 
     } 

     private void fill(File[] files) { 
       this.directoryEntries.clear(); 
       if(this.currentDirectory.getParent() != null) 
         this.directoryEntries.add(".."); 

       switch(this.displayMode){ 
         case ABSOLUTE: 
           for (File file : files){ 
             this.directoryEntries.add(file.getPath()); 
           } 
           break; 
         case RELATIVE: // On relative Mode, we have to add the current-path to the beginning 
           int currentPathStringLenght = this.currentDirectory.getAbsolutePath().length(); 
           for (File file : files){ 
             this.directoryEntries.add(file.getAbsolutePath().substring(currentPathStringLenght)); 
           } 
           break; 
       } 

     ArrayAdapter<String> directoryList = new ArrayAdapter<String>(this, R.layout.load, this.directoryEntries); 
     this.setListAdapter(directoryList); 
     } 

     protected void onListItemClick(ListView l, View v, int position, long id) { 
       int selectionRowID = position; 
       String selectedFileString = this.directoryEntries.get(selectionRowID); 
       if(selectedFileString.equals("..")){ 
         this.upOneLevel(); 
       }else if(selectedFileString.equals()){ /// what to write here ??? 
         this.readFile(); ///what to write here??? 
       } else { 
         File clickedFile = null; 
         switch(this.displayMode){ 
           case RELATIVE: 
             clickedFile = new File(this.currentDirectory.getAbsolutePath() 
                           + this.directoryEntries.get(selectionRowID)); 
             break; 
           case ABSOLUTE: 
             clickedFile = new File(this.directoryEntries.get(selectionRowID)); 
             break; 
         } 
         if(clickedFile.isFile()) 
          this.Browse(clickedFile); 
       } 
     } 

     private void readFile() { 
// what to write here??? 
     } 

Sorry i cant đưa hình ảnh bởi vì tôi không có danh tiếng, nhưng khi tôi chạy nó trên giả lập của tôi một có được một cái gì đó như này:

/mnt/sdcard/kuzmanic.c 
/mnt/sdcard/text.txt 
/mnt/sdcard/DCIM 
/mnt/sdcard/LOST.DIR 

Vì vậy, những gì tôi muốn làm là khi tôi bấm vào text.txt hoặc kuzmanic.c tập tin tôi muốn mở sau đó trong file bố trí tương tự, đó là tập tin load.xml tôi:

This is the code for the xml file: 
<?xml version="1.0" encoding="utf-8"?> 
<TextView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:textSize="18sp">  


</TextView> 

Những gì tôi cần viết trong mã của mình và tôi có phải viết gì trong tệp kê khai không ???

+0

sử dụng java.io .Use InputStream để đọc file.Same như bạn có thể sử dụng trong kỹ năng Java cốt lõi của bạn. –

Trả lời

0

tôi đã sử dụng mã này để đọc một tập tin văn bản trong thẻ SD,

public class ReadFileSDCardActivity extends Activity { 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

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

     File dir = Environment.getExternalStorageDirectory(); 
     //File yourFile = new File(dir, "path/to/the/file/inside/the/sdcard.ext"); 

     //Get the text file 
     File file = new File(dir,"text.txt"); 
     // i have kept text.txt in the sd-card 

     if(file.exists()) // check if file exist 
     { 
       //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 
      } 
      //Set the text 
      tv.setText(text); 
     } 
     else 
     { 
      tv.setText("Sorry file doesn't exist!!"); 
     } 
    } 
} 
+0

nhờ người đàn ông này làm việc tốt nhưng bây giờ tôi có một vấn đề khác ... khi tôi hiển thị văn bản nó cũng hiển thị cho tôi đường dẫn thư mục .. nhưng tôi không biết làm thế nào để loại bỏ .... –

0

đầu tiên bạn phải từ bỏ một id để TextView của bạn vào file load.xml và xác định các TextView bên trong một bố trí tuyến tính. như thế này

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" android:layout_height="match_parent" 
<TextView android:id="@+id/tv1 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:textSize="18sp"/> 

bây giờ bạn phải thiết lập cách bố trí của activity.you của bạn có thể làm điều này trong onCreate() phương pháp duy nhất.

setContentView(R.layout.load); 

giờ đây tạo đối tượng TextVew như thế này.

TextView tview = (TextView) findViewById(R.id.tv1); 

bây giờ bạn phải đọc các tập tin văn bản sử dụng FileInputStream và giữ nó vào một biến chuỗi.

sau đó bạn có thể gán chuỗi cho chế độ xem văn bản.

tview.setText(string variable name); 
7

Hãy thử mã này:

package com.javasamples; 
import java.io.*; 
import android.app.Activity; 
import android.os.Bundle; 
import android.view.*; 
import android.view.View.OnClickListener; 
import android.widget.*; 

public class FileDemo2 extends Activity { 
    // GUI controls 
    EditText txtData; 
    Button btnWriteSDFile; 
    Button btnReadSDFile; 
    Button btnClearScreen; 
    Button btnClose; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    // bind GUI elements with local controls 
    txtData = (EditText) findViewById(R.id.txtData); 
    txtData.setHint("Enter some lines of data here..."); 

    btnWriteSDFile = (Button) findViewById(R.id.btnWriteSDFile); 
    btnWriteSDFile.setOnClickListener(new OnClickListener() { 

    public void onClick(View v) { 
     // write on SD card file data in the text box 
     try { 
      File myFile = new File("/sdcard/mysdfile.txt"); 
      myFile.createNewFile(); 
      FileOutputStream fOut = new FileOutputStream(myFile); 
      OutputStreamWriter myOutWriter = 
            new OutputStreamWriter(fOut); 
      myOutWriter.append(txtData.getText()); 
      myOutWriter.close(); 
      fOut.close(); 
      Toast.makeText(getBaseContext(), 
        "Done writing SD 'mysdfile.txt'", 
        Toast.LENGTH_SHORT).show(); 
     } catch (Exception e) { 
      Toast.makeText(getBaseContext(), e.getMessage(), 
        Toast.LENGTH_SHORT).show(); 
     } 
    }// onClick 
    }); // btnWriteSDFile 

     btnReadSDFile = (Button) findViewById(R.id.btnReadSDFile); 
     btnReadSDFile.setOnClickListener(new OnClickListener() { 

     public void onClick(View v) { 
      // write on SD card file data in the text box 
     try { 
      File myFile = new File("/sdcard/mysdfile.txt"); 
      FileInputStream fIn = new FileInputStream(myFile); 
      BufferedReader myReader = new BufferedReader(
        new InputStreamReader(fIn)); 
      String aDataRow = ""; 
      String aBuffer = ""; 
      while ((aDataRow = myReader.readLine()) != null) { 
       aBuffer += aDataRow + "\n"; 
      } 
      txtData.setText(aBuffer); 
      myReader.close(); 
      Toast.makeText(getBaseContext(), 
        "Done reading SD 'mysdfile.txt'", 
        Toast.LENGTH_SHORT).show(); 
     } catch (Exception e) { 
      Toast.makeText(getBaseContext(), e.getMessage(), 
        Toast.LENGTH_SHORT).show(); 
     } 
     }// onClick 
     }); // btnReadSDFile 

     btnClearScreen = (Button) findViewById(R.id.btnClearScreen); 
     btnClearScreen.setOnClickListener(new OnClickListener() { 

      public void onClick(View v) { 
       // clear text box 
       txtData.setText(""); 
      } 
     }); // btnClearScreen 

     btnClose = (Button) findViewById(R.id.btnClose); 
     btnClose.setOnClickListener(new OnClickListener() { 

      public void onClick(View v) { 
       // clear text box 
       finish(); 
      } 
     }); // btnClose 

    }// onCreate 

}// AndSDcard 

file layout là

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 
android:id="@+id/widget28" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:background="#ff0000ff" 
android:orientation="vertical" 
xmlns:android="http://schemas.android.com/apk/res/android" 
> 
<EditText 
android:id="@+id/txtData" 
android:layout_width="fill_parent" 
android:layout_height="180px" 
android:textSize="18sp" /> 

<Button 
android:id="@+id/btnWriteSDFile" 
android:layout_width="143px" 
android:layout_height="44px" 
android:text="1. Write SD File" /> 

<Button 
android:id="@+id/btnClearScreen" 
android:layout_width="141px" 
android:layout_height="42px" 
android:text="2. Clear Screen" /> 

<Button 
android:id="@+id/btnReadSDFile" 
android:layout_width="140px" 
android:layout_height="42px" 
android:text="3. Read SD File" /> 

<Button 
android:id="@+id/btnClose" 
android:layout_width="141px" 
android:layout_height="43px" 
android:text="4. Close" /> 

</LinearLayout> 

enter image description here

Các vấn đề liên quan