Android:读取文件:在我第一次选择文件时不会打开。当我再次尝试时,它会打开文件
这是我的代码。当我第一次启动应用程序时,我尝试选择一个文件,结果代码为0。第二次单击按钮打开资源管理器时,我选择了该文件,结果代码为-1,因此它成功地打开了该文件。你知道第一次会发生什么吗?我似乎不明白为什么它会给我代码0?谢谢各位。顺便说一下,这是一个糟糕的编码,但我只是想了解Android中的文件打开过程。谢谢Android:读取文件:在我第一次选择文件时不会打开。当我再次尝试时,它会打开文件,android,Android,这是我的代码。当我第一次启动应用程序时,我尝试选择一个文件,结果代码为0。第二次单击按钮打开资源管理器时,我选择了该文件,结果代码为-1,因此它成功地打开了该文件。你知道第一次会发生什么吗?我似乎不明白为什么它会给我代码0?谢谢各位。顺便说一下,这是一个糟糕的编码,但我只是想了解Android中的文件打开过程。谢谢 public class MainActivity extends Activity implements OnClickListener { final int ACTIVITY
public class MainActivity extends Activity implements OnClickListener {
final int ACTIVITY_CHOOSE_FILE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button my_button = (Button) findViewById(R.id.activity);
my_button.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/");
startActivityForResult(intent, ACTIVITY_CHOOSE_FILE);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.v("onActivityResult","requestCode is: " + requestCode + " resultCode" + resultCode);
if ((requestCode == ACTIVITY_CHOOSE_FILE) && (resultCode == RESULT_OK)) {
Log.v("onActivityResult","Passes through if statement");
//String fileSelected = data.getStringExtra("fileSelected");
String FilePath = data.getData().getPath();
TextView my_text = (TextView) findViewById(R.id.textView1);
my_text.setText(FilePath);
StringBuilder text = null;
try{
Scanner input = new Scanner(FilePath);
//File dir = Environment.getExternalStorageDirectory();
//File yourFile = new File(dir, FilePath);
//Read text from file
text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(FilePath));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
}
catch (IOException e) {
//You'll need to add proper error handling here
}
}catch(Exception e){
Log.v("file not opened","THE FILE WAS NOT OPENED");
}
my_text.setText(text);
}
}
}
此类错误属于第三方错误,请尝试在其他设备上使用应用程序或使用emulator,然后查看运行情况。此类错误属于第三方错误,请尝试在其他设备或emulator上使用应用程序,然后查看运行情况goes@Mr.Me,我尝试了不同的文件浏览器,它们工作得很好。谢谢你的解释!。请在你的帖子上注明答案。