如何从 android 上的 sdcard 读取选定的文本文件

How to read a selected text file from sdcard on android

我是 android 开发的新手,我需要你的帮助。我锁定了与我的发展相似但对我没有帮助的主题。

到目前为止,我创建的函数可以从我的 sdcard 中获取文件并向我显示当时的列表。

这是工作

这是在 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???

    }/mnt/sdcard/kuzmanic.c

/mnt/sdcard/text.txt

/mnt/sdcard/DCIM

/mnt/sdcard/LOST.DIRThis 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>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 +"\

";

      }

      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<?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><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"/>setContentView(R.layout.load);TextView tview = (TextView) findViewById(R.id.tv1);tview.setText(string variable name);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('\

'); 

        } 

      } 

      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!!"); 

    } 

  } 

}

对不起,我不能放图像,因为我没有声誉,但是当我在我的模拟器上运行它时,会得到这样的结果:

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???

    }/mnt/sdcard/kuzmanic.c

/mnt/sdcard/text.txt

/mnt/sdcard/DCIM

/mnt/sdcard/LOST.DIRThis 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>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 +"\

";

      }

      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<?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><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"/>setContentView(R.layout.load);TextView tview = (TextView) findViewById(R.id.tv1);tview.setText(string variable name);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('\

'); 

        } 

      } 

      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!!"); 

    } 

  } 

}

所以我想要做的是当我点击我想要打开的 text.txt 或 kuzmanic.c 文件时,然后在同一个布局文件中,即我的 load.xml 文件:

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???

    }/mnt/sdcard/kuzmanic.c

/mnt/sdcard/text.txt

/mnt/sdcard/DCIM

/mnt/sdcard/LOST.DIRThis 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>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 +"\

";

      }

      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<?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><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"/>setContentView(R.layout.load);TextView tview = (TextView) findViewById(R.id.tv1);tview.setText(string variable name);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('\

'); 

        } 

      } 

      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!!"); 

    } 

  } 

}

我需要在我的代码中写什么,我必须在清单中写什么???


试试这个代码:

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???

    }/mnt/sdcard/kuzmanic.c

/mnt/sdcard/text.txt

/mnt/sdcard/DCIM

/mnt/sdcard/LOST.DIRThis 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>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 +"\

";

      }

      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<?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><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"/>setContentView(R.layout.load);TextView tview = (TextView) findViewById(R.id.tv1);tview.setText(string variable name);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('\

'); 

        } 

      } 

      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!!"); 

    } 

  } 

}

布局文件是

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???

    }/mnt/sdcard/kuzmanic.c

/mnt/sdcard/text.txt

/mnt/sdcard/DCIM

/mnt/sdcard/LOST.DIRThis 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>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 +"\

";

      }

      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<?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><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"/>setContentView(R.layout.load);TextView tview = (TextView) findViewById(R.id.tv1);tview.setText(string variable name);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('\

'); 

        } 

      } 

      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!!"); 

    } 

  } 

}

如何从 android 上的 sdcard 读取选定的文本文件


首先,您必须在 load.xml 文件中为您的 textview 提供一个 id,并在线性布局中定义 textview。像这样

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???

    }/mnt/sdcard/kuzmanic.c

/mnt/sdcard/text.txt

/mnt/sdcard/DCIM

/mnt/sdcard/LOST.DIRThis 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>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 +"\

";

      }

      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<?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><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"/>setContentView(R.layout.load);TextView tview = (TextView) findViewById(R.id.tv1);tview.setText(string variable name);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('\

'); 

        } 

      } 

      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!!"); 

    } 

  } 

}

现在您必须设置活动的布局。您只能在 onCreate() 方法中执行此操作。

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

        				

相关推荐

  • Spring部署设置openshift

    Springdeploymentsettingsopenshift我有一个问题让我抓狂了三天。我根据OpenShift帐户上的教程部署了spring-eap6-quickstart代码。我已配置调试选项,并且已将Eclipse工作区与OpehShift服务器同步-服务器上的一切工作正常,但在Eclipse中出现无法消除的错误。我有这个错误:cvc-complex-type.2.4.a:Invali…
    2025-04-161
  • 检查Java中正则表达式中模式的第n次出现

    CheckfornthoccurrenceofpatterninregularexpressioninJava本问题已经有最佳答案,请猛点这里访问。我想使用Java正则表达式检查输入字符串中特定模式的第n次出现。你能建议怎么做吗?这应该可以工作:MatchResultfindNthOccurance(intn,Patternp,CharSequencesrc){Matcherm=p.matcher…
    2025-04-161
  • 如何让 JTable 停留在已编辑的单元格上

    HowtohaveJTablestayingontheeditedcell如果有人编辑JTable的单元格内容并按Enter,则内容会被修改并且表格选择会移动到下一行。是否可以禁止JTable在单元格编辑后转到下一行?原因是我的程序使用ListSelectionListener在单元格选择上同步了其他一些小部件,并且我不想在编辑当前单元格后选择下一行。Enter的默认绑定是名为selectNext…
    2025-04-161
  • Weblogic 12c 部署

    Weblogic12cdeploy我正在尝试将我的应用程序从Tomcat迁移到Weblogic12.2.1.3.0。我能够毫无错误地部署应用程序,但我遇到了与持久性提供程序相关的运行时错误。这是堆栈跟踪:javax.validation.ValidationException:CalltoTraversableResolver.isReachable()threwanexceptionatorg.…
    2025-04-161
  • Resteasy Content-Type 默认值

    ResteasyContent-Typedefaults我正在使用Resteasy编写一个可以返回JSON和XML的应用程序,但可以选择默认为XML。这是我的方法:@GET@Path("/content")@Produces({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})publicStringcontentListRequestXm…
    2025-04-161
  • 代码不会停止运行,在 Java 中

    thecodedoesn'tstoprunning,inJava我正在用Java解决项目Euler中的问题10,即"Thesumoftheprimesbelow10is2+3+5+7=17.Findthesumofalltheprimesbelowtwomillion."我的代码是packageprojecteuler_1;importjava.math.BigInteger;importjava…
    2025-04-161
  • Out of memory java heap space

    Outofmemoryjavaheapspace我正在尝试将大量文件从服务器发送到多个客户端。当我尝试发送大小为700mb的文件时,它显示了"OutOfMemoryjavaheapspace"错误。我正在使用Netbeans7.1.2版本。我还在属性中尝试了VMoption。但仍然发生同样的错误。我认为阅读整个文件存在一些问题。下面的代码最多可用于300mb。请给我一些建议。提前致谢publicc…
    2025-04-161
  • Log4j 记录到共享日志文件

    Log4jLoggingtoaSharedLogFile有没有办法将log4j日志记录事件写入也被其他应用程序写入的日志文件。其他应用程序可以是非Java应用程序。有什么缺点?锁定问题?格式化?Log4j有一个SocketAppender,它将向服务发送事件,您可以自己实现或使用与Log4j捆绑的简单实现。它还支持syslogd和Windows事件日志,这对于尝试将日志输出与来自非Java应用程序…
    2025-04-161