我想在Android项目中读取文件。但我的代码不起作用。你能帮忙吗?
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.");
}
将sozluk.txt
放入<your project dir>assetssozluk.txt
,并使用进行访问
BufferedReader oku = new BufferedReader(new InputStreamReader(getAssets().open(dosyaAdi)));
如果您将代码放入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());
}
}
}
Danial代码是绝对正确的,但在Android6.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();
}
}
}