Jak mogę odczytać plik tekstowy w systemie Android?

116

Chcę przeczytać tekst z pliku tekstowego. W poniższym kodzie występuje wyjątek (oznacza to, że przechodzi do catchbloku). Umieściłem plik tekstowy w folderze aplikacji. Gdzie mam umieścić ten plik tekstowy (mani.txt), aby go poprawnie przeczytać?

    try
    {
        InputStream instream = openFileInput("E:\\test\\src\\com\\test\\mani.txt"); 
        if (instream != null)
        {
            InputStreamReader inputreader = new InputStreamReader(instream); 
            BufferedReader buffreader = new BufferedReader(inputreader); 
            String line,line1 = "";
            try
            {
                while ((line = buffreader.readLine()) != null)
                    line1+=line;
            }catch (Exception e) 
            {
                e.printStackTrace();
            }
         }
    }
    catch (Exception e) 
    {
        String error="";
        error=e.getMessage();
    }
user1635224
źródło
4
co masz nadzieję, że twój emulator jest częścią twojego s / m? „E: \\ test \\ src \\ com \\ test \\ mani.txt”
Athul Harikumar,
2
z której lokalizacji chcesz odczytać plik tekstowy ...?
Sandip Armal Patil
2
InputStream iS = resources.getAssets (). Open (fileName); (jeśli umieścisz plik w aktywach)
Athul Harikumar
1
@Sandip faktycznie skopiowałem plik tekstowy (mani.txt) i umieścić go w folderze aplikacji Android (folder mającego .settings, bin, bibliotekami, SRC, aktywów, gen, Res, androidmanifeast.xml)
user1635224
2
lub wstaw po prostu folder res / raw i sprawdź moją zaktualizowaną odpowiedź.
Sandip Armal Patil,

Odpowiedzi:

242

Spróbuj tego :

Zakładam, że twój plik tekstowy znajduje się na karcie SD

    //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.toString());

poniższe linki również mogą Ci pomóc:

Jak mogę odczytać plik tekstowy z karty SD w systemie Android?

Jak czytać plik tekstowy w systemie Android?

Android czyta tekstowy nieprzetworzony plik zasobów

Shruti
źródło
3
Twój link pomógłby mi to osiągnąć
user1635224
10
BufferedReader musi zostać zamknięty na końcu!
RainClick
2
Jeśli masz jeden pusty wiersz w dokumencie txt, ten parser przestanie działać! Rozwiązaniem jest przyznanie się do tych pustych rzędów: while ((line = br.readLine()) != null) { if(line.length() > 0) { //do your stuff } }
Choletski
@Shruti jak dodać plik na kartę SD
Tharindu Dhanushka
@Choletski, dlaczego mówisz, że przestanie działać? Jeśli istnieje pusty wiersz, zostanie on dołączony do tekstu StringBuilder. Jaki jest problem?
LarsH
28

Jeśli chcesz odczytać plik z karty SD. Poniższy kod może być dla Ciebie pomocny.

 StringBuilder text = new StringBuilder();
    try {
    File sdcard = Environment.getExternalStorageDirectory();
    File file = new File(sdcard,"testFile.txt");

        BufferedReader br = new BufferedReader(new FileReader(file));  
        String line;   
        while ((line = br.readLine()) != null) {
                    text.append(line);
                    Log.i("Test", "text : "+text+" : end");
                    text.append('\n');
                    } }
    catch (IOException e) {
        e.printStackTrace();                    

    }
    finally{
            br.close();
    }       
    TextView tv = (TextView)findViewById(R.id.amount);  

    tv.setText(text.toString()); ////Set the text to text view.
  }

    }

Jeśli chcesz odczytać plik z folderu zasobów, to

AssetManager am = context.getAssets();
InputStream is = am.open("test.txt");

Lub jeśli chcesz odczytać ten plik z folderu res/raw, w którym plik zostanie zindeksowany i będzie dostępny przez id w pliku R:

InputStream is = getResources().openRawResource(R.raw.test);     

Dobry przykład odczytu pliku tekstowego z folderu res / raw

Sandip Armal Patil
źródło
2
brjest poza zakresem w ostatnim bloku.
AlgoRythm
3

Najpierw przechowujesz plik tekstowy w folderze raw.

private void loadWords() throws IOException {
    Log.d(TAG, "Loading words...");
    final Resources resources = mHelperContext.getResources();
    InputStream inputStream = resources.openRawResource(R.raw.definitions);
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

    try {
        String line;
        while ((line = reader.readLine()) != null) {
            String[] strings = TextUtils.split(line, "-");
            if (strings.length < 2)
                continue;
            long id = addWord(strings[0].trim(), strings[1].trim());
            if (id < 0) {
                Log.e(TAG, "unable to add word: " + strings[0].trim());
            }
        }
    } finally {
        reader.close();
    }
    Log.d(TAG, "DONE loading words.");
}
Baran
źródło
2

Wypróbuj ten kod

public static String pathRoot = "/sdcard/system/temp/";
public static String readFromFile(Context contect, String nameFile) {
    String aBuffer = "";
    try {
        File myFile = new File(pathRoot + nameFile);
        FileInputStream fIn = new FileInputStream(myFile);
        BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
        String aDataRow = "";
        while ((aDataRow = myReader.readLine()) != null) {
            aBuffer += aDataRow;
        }
        myReader.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return aBuffer;
}
HuynhHan
źródło
0

Spróbuj tego

try {
        reader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
      String line="";
      String s ="";
   try 
   {
       line = reader.readLine();
   } 
   catch (IOException e) 
   {
       e.printStackTrace();
   }
      while (line != null) 
      {
       s = s + line;
       s =s+"\n";
       try 
       {
           line = reader.readLine();
       } 
       catch (IOException e) 
       {
           e.printStackTrace();
       }
    }
    tv.setText(""+s);
  }
Muhammad Usman Ghani
źródło