Android'de bir metin dosyasını nasıl okuyabilirim?


117

Metni bir metin dosyasından okumak istiyorum. Aşağıdaki kodda, bir istisna meydana gelir (bu, catchbloğa gittiği anlamına gelir ). Metin dosyasını uygulama klasörüne koydum. Bu metin dosyasını (mani.txt) doğru okuyabilmek için nereye koymalıyım?

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

4
emülatörünüzün s / m'nizin bir parçası olmasını umuyorsunuz? "E: \\ test \\ src \\ com \\ test \\ mani.txt"
Athul Harikumar

2
metin dosyasını hangi konumdan okumak istiyorsunuz ...?
Sandip Armal Patil

2
InputStream iS = kaynaklar.getAssets (). Open (dosyaAdı); (dosyayı varlıklara koyarsanız)
Athul Harikumar

1
@Sandip aslında metin dosyasını (mani.txt) kopyaladım ve android uygulamasının klasörüne koydum (.settings, bin, libs, src, assets, gen, res, androidmanifeast.xml içeren klasör)
user1635224

2
veya res / raw klasörüne koyun ve güncellenmiş cevabımı kontrol edin.
Sandip Armal Patil

Yanıtlar:


244

Bunu dene :

Metin dosyanızın sd kartta olduğunu varsayıyorum

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

Aşağıdaki bağlantılar da size yardımcı olabilir:

Android'de SD karttan bir metin dosyasını nasıl okuyabilirim?

Android'de metin dosyası nasıl okunur?

Android ham metin kaynak dosyasını oku


3
bağlantınız elde
etmeme

10
BufferedReader'ın sonunda kapanması gerekiyor!
RainClick 01

2
Txt belgenizde bir boş satır varsa, bu ayrıştırıcı çalışmayı durduracaktır! Çözüm, bu boş satırların olduğunu kabul while ((line = br.readLine()) != null) { if(line.length() > 0) { //do your stuff } }
etmektir

@Shruti dosyası SD karta nasıl eklenir
Tharindu Dhanushka

@Choletski, neden çalışmayı bırakacağını söylüyorsun? Boş bir satır varsa, boş satır StringBuilder metnine eklenecektir. Sorun ne?
LarsH

29

Dosyayı sd karttan okumak istiyorsanız. O zaman aşağıdaki kod sizin için yararlı olabilir.

 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.
  }

    }

Dosyayı varlık klasöründen okumak isterseniz

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

Veya Bu dosyayı res/raw, dosyanın indeksleneceği ve R dosyasındaki bir id ile erişilebileceği klasörden okumak isterseniz :

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

Res / raw klasöründen metin dosyası okumaya iyi bir örnek


2
brNihayet bloğunda kapsam dışında.
AlgoRythm


3

Önce metin dosyanızı ham klasöre kaydedersiniz.

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.");
}

3

Bu kodu dene

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;
}

1

Bunu dene

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);
  }
Sitemizi kullandığınızda şunları okuyup anladığınızı kabul etmiş olursunuz: Çerez Politikası ve Gizlilik Politikası.
Licensed under cc by-sa 3.0 with attribution required.