1

I want read file in Android Project. But my code is not working. Can you help?

            String dosyaAdi = "sozluk.txt";
        String satir;
        try{
            BufferedReader oku = new BufferedReader(new FileReader(dosyaAdi));
            satir = oku.readLine();
            while (satir != null) {
                tvDeneme.setText(satir);
                satir = oku.readLine();
            }
            oku.close();
        }
        catch (IOException iox){
            System.out.println(dosyaAdi+" adli dosya okunamiyor.");
        }
Mazlum Ağar
  • 41
  • 11

3 Answers3

2

Put sozluk.txt to <your project dir>\assets\sozluk.txt, and access it with:

BufferedReader oku = new BufferedReader(new InputStreamReader(getAssets().open(dosyaAdi)));
Daniel Fekete
  • 4,988
  • 3
  • 23
  • 23
1

If you are putting the code inside the mainActivity, (change the code accordingly to the activity

try
        {
            MainActivity.context = getApplicationContext();
            AssetManager am = context.getAssets();
            InputStream instream = am.open("sozluk.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;
                        Log.e("File Read", line.toString());
                    }
                }catch (Exception e) 
                {
                    e.printStackTrace();
                    Log.e("Exception Occurred", "Exception Occurred"+e.getMessage());
                }
             }
        }
shanavascet
  • 589
  • 1
  • 4
  • 18
1

Danial code is absolutely right but after Android 6.0 (API level 23) they have introduced run time permission. Place your read file code in below success block.

public class MainActivity extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback{

  private static final int REQUEST_WRITE_PERMISSION = 786;

  @Override
  public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    if (requestCode == REQUEST_WRITE_PERMISSION && grantResults[0] == PackageManager.PERMISSION_GRANTED) {            
        readFile();
    }
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    requestPermission();
  }

  private void requestPermission() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_PERMISSION);
    } else {
        readFile();
    }
  }
}
markus
  • 31
  • 2