I am getting a FileNotFoundException but the file is there - java

When I try to open a file that I selected via an Intent I get this error:
java.io.FileNotFoundException:
/document/primary:Android/data/com.oli.myapp/Files/test.xml: open
failed: ENOENT (No such file or directory)
I don't know why this happens. The file exists because I selected it. Here is my Code:
File selection:
Intent chooseFileXML = new Intent(Intent.ACTION_GET_CONTENT);
Uri uri = Uri.parse(new Helper(FunctionsActivity.this).getPathToAppFolder());
chooseFileXML.setDataAndType(uri, "text/xml");
Intent intentXML = Intent.createChooser(chooseFileXML, getString(R.string.importXMLDatei));
startActivityForResult(intentXML, REQUEST_CODE_IMPORT_XML_FILE);
Code to get it:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
switch (requestCode){
case REQUEST_CODE_IMPORT_XML_FILE:
if(resultCode == RESULT_OK){
String Fpath = data.getDataString();
File file = new File(Fpath);
Intent intent = new Intent(FunctionsActivity.this, CreateActivity.class);
intent.setAction(Intent.ACTION_DEFAULT);
intent.setData(Uri.parse(file.toURI().toString()));
startActivity(intent);
}
break;
}
}
EDIT:
Uri uri = data.getData();
DocumentFile documentFile = DocumentFile.fromSingleUri(this, uri);
String type = documentFile.getType();
if(type.equals("text/xml")){
try {
InputStream inputStream = getContentResolver().openInputStream(uri);
if(inputStream == null){
throw new Exception();
}
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line).append('\n');
}
//Could read the file with no problems
createWithXMLCode(total.toString());
}catch (Exception e){
e.printStackTrace();
//TODO
}
}else{
//TODO
}

ACTION_GET_CONTENT gives you a Uri. What the user chooses through ACTION_GET_CONTENT does not have to be a file at all, let alone one you can access. In this case, you are getting a Uri back with a content scheme, which is very common.
Use a ContentResolver and methods like getInputStream() to work with the content represented by that Uri.

Related

not able to get full real path with name of selected file [duplicate]

This question already has answers here:
Android Kotlin: Getting a FileNotFoundException with filename chosen from file picker?
(5 answers)
Android - Get real path of a .txt file selected from the file explorer
(1 answer)
Closed 2 years ago.
I am not geting currect path var name "FilePath" im geting value E/File path: /document/29 but my selected file stored in downloads folder file name is "test.xlsx" i need original path with file name with file extention to pass in FileInputStream().I am not able to fix it ...can anybody give the code
btnimport.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent fileintent = new Intent(Intent.ACTION_GET_CONTENT);
fileintent.setType("*/*");
try {
startActivityForResult(fileintent, requestcode);
} catch (ActivityNotFoundException e) {
lbl.setText("No activity can handle picking a file. Showing alternatives.");
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null)
return;
switch (requestCode) {
case requestcode:
String FilePath = data.getData().getPath();
Log.e("File path", FilePath);
if (FilePath.contains("/root_path"))
FilePath = FilePath.replace("/root_path", "");
Log.e("New File path", FilePath);
try {
if (resultCode == RESULT_OK) {
AssetManager am = this.getAssets();
InputStream inStream;
Workbook wb = null;
try {
inStream = new FileInputStream(FilePath);
Log.e("Extension",FilePath.substring(FilePath.lastIndexOf(".")));
if (FilePath.substring(FilePath.lastIndexOf(".")).equals(".xls")) {
Log.e("File Type", "Selected file is XLS");
wb = new HSSFWorkbook(inStream);
}
else if (FilePath.substring(FilePath.lastIndexOf(".")).equals(".xlsx")) {
Log.e("File Type", "Selected file is XLSX");
wb = new XSSFWorkbook(inStream);
}
else {
wb = null;
lbl.setText("Please select a valid Excel file");
return;
}
inStream.close();
i need original path with file name with file extention to pass in FileInputStream().
No you do not need 'a real path' as you better use the obtained uri to open an input stream.
InputStream is = getContentResolver().openInputStream(data.getData());
Use that stream as if it was your wanted stream.

Retrieving file on sdcard with this path: "/document/primary:..."

I'm trying to read contents of a CSS file, which is on my SDCARD.
I'm selecting the file from a action:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("text/css");
startActivityForResult(intent, 1);
Here I grab the path:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
SharedPreferences sharedPref = PreferenceManager
.getDefaultSharedPreferences(getActivity().getApplicationContext());
SharedPreferences.Editor editor = sharedPref.edit();
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
Log.d("FilePicker", data.getData().toString());
editor.putString("custom_style_file", data.getData().getPath());
editor.commit();
}
if (resultCode == Activity.RESULT_CANCELED) {
//Write your code if there's no result
}
}
}
I get the following path /document/primary:CustomCSS/myCustom.css
Then i try to read the contents of the file with this function:
public static String readFromSDcard(String path) {
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard, path);
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
}
br.close();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
Log.d("Read from file", text.toString());
return text.toString();
}
The function returns nothing, and I'm not sure what I'm doing wrong here.
//You'll need to add proper error handling here
If you do so you will see why your function returns nothing.
For instance:
text.append("IOException: " + e.getMessage() + "\n");
Your path:
/document/primary:CustomCSS/myCustom.css
That is not a file syctem path but a content provider path.
So get a content resolver and then let it open an input stream for the file. After that you can use the usual code to read the contents.
Google for getContentResolver().openInputStream().
Make sure you have the the read storage permission in your manifest file
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Getting Uri of a saved image file

When I pick an image from gallery, I can get the Uri for that image as given below:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent result) {
if (requestCode == Crop.REQUEST_PICK && resultCode == RESULT_OK) {
Uri uri = result.getData();
beginCrop(uri);
} else if (requestCode == Crop.REQUEST_CROP) {
handleCrop(resultCode, result);
}
}
The format of the Uri retrieved above is content://media/external/images/media/7266
However, I am unable to retrieve a Uri in this format when I try to fetch the Uri of an image I just saved as a file:
Date d = new Date();
CharSequence s = DateFormat.format("MM-dd-yy hh-mm-ss", d.getTime());
Bitmap bitmap = drawView.getResultBitmap();
File sdCardDirectory = Environment.getExternalStorageDirectory();
File image = new File(sdCardDirectory, "DCIM/Camera/" + s.toString() + ".png");
boolean success = false;
// Encode the file as a PNG image.
FileOutputStream outStream;
try {
outStream = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
/* 100 to keep full quality of the image */
outStream.flush();
outStream.close();
success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (success) {
MediaScannerConnection.scanFile(getActivity(), new String[]{
image.getAbsolutePath()},
null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
}
});
Uri uri = Uri.parse(image.getAbsolutePath());
beginCrop(uri);
The Uri obtained from above code is /storage/emulated/0/DCIM/Camera/02-04-16 12-49-16.png
I believe, this is not the correct Uri format, instead just absolute file path. Is there a way out by which I can get the Uri in the format content://media/external/images/media/ ?
Any help is much appreciated
I believe, this is not the correct Uri format, instead just absolute file path.
You are correct. Use Uri.fromFile() to convert a File into a Uri pointing to the file.
Is there a way out by which I can get the Uri in the format content://media/external/images/media/ ?
Not readily. At best, in onScanCompleted(), you might be able to run some query to get the Uri that the MediaStore uses. But, until then, MediaStore does not know about the file.
The Uri that you get from Uri.fromFile() is a valid Uri, but it will have a file scheme, not a content scheme.
you can get uri from Bitmap like this :
Uri getUri(Context context, Bitmap bitmap) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
String path = "";
try {
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
path = MediaStore.Images.Media.insertImage(
context.getContentResolver(), bitmap, "Title", null);
} catch (Exception e) {
}
return Uri.parse(path);
}

How to get file path of any text file and read it from SD card in Android?

I have got so many links related to image file but didn't get any text related. There is solution for specific text file to open but I need general solution and not hard coded file location on SD card. I'm building an Android app that gets (copyies) the link of the file in TextView and reads the content of that file in another TextView from SD card. One button which is used to open the SD card:
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("text/plain"); //open only for text file
intent.setAction(Intent.ACTION_GET_CONTENT);
//broadcast the supported media to choose for file to open
startActivityForResult(Intent.createChooser(intent, "Select file"), MY_INTENT_CLICK);
}
This is the code for onActivityResult()
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == MY_INTENT_CLICK) {
if (data == null) return;
//String sel_file_path;
String sel_file_path;
Uri sel_file_uri = data.getData();
sel_file_path = FileText.getPath (getApplicationContext(), sel_file_uri);
setTextViews (sel_file_path);
}
}
}
After getting the file path from FileText it views the link and content of text file using this method.
//show the link and display the content of the file
private void setTextViews(String sel_file_path) {
//copy the file link to textview
this.txtpath.setText("File path: " +sel_file_path);
//display the text file
try {
File file1 = new File(sel_file_path);
//System.out.println("Path : " + file1);
FileInputStream fis = new FileInputStream(file1);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String datatoread = "";
String inBuffer = "";
//Read the line of the file, store it in temporary variable and append it to inBuffer
while ((datatoread = br.readLine()) != null) {
inBuffer += datatoread + "\n";
}
txtdsp.setText(inBuffer);
br.close();
//Toast.makeText(getBaseContext(), "Load file reading", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
Log.d("MainActivity", "File Path: "+sel_file_path);
}
I got the an error while running on a device:
no such file or directory

Android mediaplayer won't load Uri with path /documents/audio:1159

I'm trying to play audio files with the built in mediaplayer in Android Studio. I'm using the code below to call an intent and open a third party file manager to get a files Uri and from that the file path whoich I store somewhere. Anyway, if I use a file manager like ES File Explorer I get a path that looks like "/sdcard/some directory/test.mp3" however, if I use the built in file explorer I get a path like "/documents/audio:1159" for the same file. I understand that the latter is an "asset" but when I try to feed this into mediaplayer I get an exception. What am I doing wrong?
The code below shows the intent method I'm using to get the filepath and the code below that shows how I use that file path to get a Uri and feed this into mediaplayer. Just to be clear file paths like "/sdcard/some directory/test.mp3" work fine. File paths like "/documents/audio:1159" don't.
final View.OnClickListener mGlobal_OnClickListener = new View.OnClickListener() {
public void onClick(final View v) {
int resID2 = v.getId();
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("audio/*");
try {
startActivityForResult(intent,resID2); }
catch (Exception e) {
Toast.makeText(getApplicationContext(), "Please install a file manager",Toast.LENGTH_LONG).show();
}
}
};
public void onActivityResult(int requestCode, int resultCode, Intent result) {
if (resultCode == RESULT_OK)
{
Uri data = result.getData();
String thePath = data.getPath();
// Do something with the file path
}
}
Code used to start mediaplayer based on the file path retrieved from above
Uri myUri = Uri.parse(filePath);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(getApplicationContext(), myUri);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {}
I guess you cannot use Uri like
/documents/audio:1159
when uses Intent MediaPlayer
EDITTED:
Try this code for getting filepath from assets folder
AssetManager am = getAssets();
InputStream inputStream = am.open(file:///android_asset/myfoldername/myfilename);
File file = createFileFromInputStream(inputStream);
private File createFileFromInputStream(InputStream inputStream) {
try{
File f = new File(my_file_name);
OutputStream outputStream = new FileOutputStream(f);
byte buffer[] = new byte[1024];
int length = 0;
while((length=inputStream.read(buffer)) > 0) {
outputStream.write(buffer,0,length);
}
outputStream.close();
inputStream.close();
return f;
}catch (IOException e) {
//Logging exception
}
return null;
}

Categories