Reputation: 31
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.");
}
Upvotes: 1
Views: 1463
Reputation: 31
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();
}
}
}
Upvotes: 1
Reputation: 589
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());
}
}
}
Upvotes: 1
Reputation: 5028
Put sozluk.txt
to <your project dir>\assets\sozluk.txt
, and access it with:
BufferedReader oku = new BufferedReader(new InputStreamReader(getAssets().open(dosyaAdi)));
Upvotes: 2