I am working on an app that takes the .txt file from a phone as input and prints it on the TextView,
public class MainActivity extends AppCompatActivity {
Button button;
Intent intent;private StringBuilder text = new StringBuilder();
private InputStream getResources(String s) {
return null;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("text/plain");
startActivityForResult(intent, 7);
Log.v("###", "parent " + getParent());
}
});
} @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
String Fpath = data.getDataString();
// final String fileName = ""+Fpath;
Log.v("###", "yo " +Fpath);
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 7:
if (resultCode == RESULT_OK) {
setContentView(R.layout.activity_main);
Log.v("###", "hellow");
setContentView(R.layout.activity_main);
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("filename.txt")));
//change code
// do reading
String mLine;
while ((mLine = reader.readLine()) != null) {
text.append(mLine);
text.append('\n');
}
} catch (IOException e) {
String PathHolder = data.getData().getPath();
Toast.makeText(MainActivity.this, PathHolder, Toast.LENGTH_LONG).show();
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
TextView output = (TextView) findViewById(R.id.Txt);
output.setText((CharSequence) text);
}
}
}
}
}
everything is good but the line
new InputStreamReader(getAssets().open("filename.txt")));
Taking the file from Assets folder,
Help me to get the file from My phone,
The file from Assets folder opening properly but I want it to be select from my phone
解决方案
You can get file path in onActivityResult which you selected from file manager.
Uri PathHolder = data.getData();
UPDATE
Above line give you uri of file which you selected from storage. Then You can get File from that Uri easily.
Just forgot about getAssets Use Following method to read from file.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Uri PathHolder = data.getData();
FileInputStream fileInputStream = null;
StringBuilder text = new StringBuilder();
try {
InputStream inputStream = getContentResolver().openInputStream(PathHolder);
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
String mLine;
while ((mLine = r.readLine()) != null) {
text.append(mLine);
text.append('\n');
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}