我想在Android Project中读取文件

时间:2014-04-08 19:46:55

标签: android file

我想在Android Project中读取文件。但我的代码不起作用。你能帮我吗?

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

3 个答案:

答案 0 :(得分:1)

Danial代码绝对正确,但在Android 6.0(API级别23)之后,他们引入了运行时权限。将读取的文件代码放在下面的成功块中。

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

答案 1 :(得分:0)

sozluk.txt添加到<your project dir>\assets\sozluk.txt,然后使用以下命令进行访问:

BufferedReader oku = new BufferedReader(new InputStreamReader(getAssets().open(dosyaAdi)));

答案 2 :(得分:0)

如果要将代码放在mainActivity中,(相应地将代码更改为活动

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