I am writing an app to create a folder on my Nexus 5 and then write a text file inside the folder.
The above part is working just fine. I am writting using the following code:
Creating the folder:
File sdCard1 = Environment.getExternalStorageDirectory();
File dir = new File(sdCard1.getAbsolutePath() + "/SmsApp");
if (dir.isDirectory())
{
String[] children = dir.list();
for (int i = 0; i < children.length; i++)
{
new File(dir, children[i]).delete();
}
}
File sdCard = Environment.getExternalStorageDirectory();
directory = new File (sdCard.getAbsolutePath() + "/SmsApp");
directory.mkdirs();
And writing the string to text file.
public void writeToText(String texttosave)
{
File sdCard = Environment.getExternalStorageDirectory();
File logFile = new File(sdCard.getAbsolutePath() + "/SmsApp" + "/smsrawdata.file");
if (!logFile.exists())
{
try
{
logFile.createNewFile();
}
catch (IOException e)
{
e.printStackTrace();
}
}
try
{
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(texttosave);
buf.newLine();
buf.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
Text file is showing up properly on my phone but when I am trying to access the same folder on phone I can't see the folder at all.
I thought it would be the same for other app on play store that creates a folder but then everything gets created and then I can see them on Windows Explorer.
Am I doing something wrong in the code part for it not to show on my Computer but show only on my phone. I am using ES File Explorer to see files on my phone.
Please let me know if someone else is having the same problem.
Thanks!
Your pc will communicate with the media store about files. Not directly with the sdcard or external memory. If the media store does not know about your file your pc can not see it. You forgot to tell the store that you created a file. For every new file you should invoke the media scanner for that file. You are not the first one who happens this so the problem has been reported many times. You only need to add a few lines of code which you will find easily searching this site for invoking media scanner on new file. If you switch off/on your device the file will be known soon too.
Related
I have an issue with my sharing option.
The option was perfectly well working (and I have saved it before trying some modifications) but I have tried to modify something and I cannot reach my goal).
The purpose is : click on the option in a menu, click on share, if the folder "test folder" doesn't exists in the "MUSIC" folder, create it, if it already exists, copie the sound, put it in the folder previously created and then use it as an extra in a SEND intent.
case R.id.share:
if (isStoragePermissionGranted()) {
File outputFile = new File("");
InputStream is = getResources().openRawResource(((Sound) adapter.getItem(index)).getMpsound());
try {
File outputDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC), "Test folder");
outputFile = new File(outputDir, getResources().getResourceEntryName(((Sound) adapter.getItem(index)).getMpsound()) + ".mp3");
if (outputDir.exists()) {
byte[] buffer = new byte[is.available()];
is.read(buffer);
OutputStream os = new FileOutputStream(outputFile);
os.write(buffer);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("audio/*");
share.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", outputFile));
share.putExtra(Intent.EXTRA_TEXT, "\"" + ((Sound) adapter.getItem(index)).getTitle_show() + "\" shared by my app");
startActivity(Intent.createChooser(share, "Share Sound File"));
} else {
outputDir.createNewFile(); //plus add code as below to share the sound after creating the folder
}
} catch (IOException e) {
e.printStackTrace();
}
}
I'm not able to create the folder and if I create it manually, the code is working well because the mp3 appears in the folder, and right after I have an error that says :
java.lang.IllegalArgumentException: Failed to find configured root that contains /storage/emulated/0/Music/my app/sound_test.mp3
So... the app is able to access the folder to create the sound but for an unknown reason, I have this issue.
What did I do wrong ?
So, for the ones who are coming in few days, months, years with the same problem :
As CommonsWare said it, the issue in accessing the folder was from the FileProvider. After configure it properly with the good path, I had no more issue.
For the part concerning the creation of a new folder, .createNewFile() doesn't seems to be the right way. It's necessarry to use .mkdir()
And to end it, the part concerning the delete of the files in the folder, you will have your answer there :
File dir = new File(Environment.getExternalStorageDirectory()+"Dir_name_here");
if (dir.isDirectory())
{
String[] children = dir.list();
for (int i = 0; i < children.length; i++)
{
new File(dir, children[i]).delete();
}
}
Source : How to delete all files in a directory java android app? Current code is deleting the that folder
I'm using the openFileOutput() to create a new txt file. I need the file to be visible from other applications (as well as from a PC when the Android device is connected via USB. Ive tried using .setReadable(true); but this does not seem valid. Please advise how I should declare the file is visible / public.
try {
textIncoming.append("saving");
final String STORETEXT = "test.txt";
OutputStreamWriter out = new OutputStreamWriter(openFileOutput(STORETEXT, 0));
out.setReadable(true);
out.write("testing");
out.close();
}
catch (Throwable t) {
textIncoming.append("not saving");
}
Ive changed my program to use getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), but for some reason it returns a path /storage/emulated/0/Documents, and I cant even find this folder on the device. Ive looked at the files on the android device using ES file explorer but cant find the folder or file I'm trying to create (Plus I want these in an documents folder on the SD card, so it seems that its not giving me a pointer to the SD card at all, and not creating the folder, and not creating the file. Following is my updated code, please advise
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).toString();
File myDir = new File(root + "/Saved_Receipts");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "DRcpt-" + n + ".xml";
textIncoming.append(root);
File file = new File(myDir, fname);
if (file.exists()) {
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
out.flush();
out.close();
}
catch (Exception e) {
e.printStackTrace();
}
Save it to sdcard if you want anyone to be able to read it.
This android documentation should tell you what you need to do.
https://developer.android.com/guide/topics/data/data-storage.html#filesExternal
openFileOutput() documentation says:
Open a private file
So the file that it creates won't be visible to other apps, unless you copy it to another directory that is visible. In that case, you have to save your data in what's called "external storage" which is shared with other apps. Use the code at this link.
public void write(View view)
{
String state;
File Dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
if (!Dir.exists())
{
Dir.mkdir();
}
File file = new File(Dir,"nahk.txt");
Toast.makeText(getApplicationContext(),file.getAbsolutePath(), Toast.LENGTH_SHORT).show();
String Message = "5nahk";
try {
FileOutputStream FOS = new FileOutputStream(file);
FOS.write(Message.getBytes());
FOS.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I have added write permission in the manifest xml file. This method is called when I press a button. The toast says that the txt file is saved in the Download folder of my Internal Storage (since I don't have an SD card in my LG G3). I open the file location (using FileManager on my LG G3) and there is no "nahk.txt" in that folder. Why can't I see the file?
I'm not familiar with native android development but I encountered something similar using cordova. After saving a file the file was not visible browsing with a usb cable but it was actually there. To see it had to restart my device.
So you could try to restart your device and check if it is still invisible (or create a method which fetches or checks the existence of the saved file to check if it is there).
edit: I learned this by googling so you should find it also
Try this
File Dir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Your_Folder_Name";
File file = new File(Dir,"nahk.txt");
this file will save inside of your device storage Your_Folder_Name
I know this is a popular question but I have looked at all of the other responses and none of them seem to work. What I want to do is write some code to a text file. My first question: is there a way to view that text file without writing code to the console? Second, I dont know where in my phone it goes and I want to see it to help trouble shoot, so if you know how to do that too, it would be great. So now I will give you an overview of what is happening. When I start my program it checks to see if the file exists, if it doesn't it reads a file out of my assets folder and copies that info and sends it to a file into the sd card. If it exits it reads the info from the sd card. Next if I press a button and change numbers and print it to my sd card again then I close it using task managers then when I come back the original information is here. I don't feel like it is being able to find my sd card location. So far I have used.
File outfilepath = Environment.getExternalStorageDirectory();
String FileName = "ExSettings.txt" ;
File outfile = new File(outfilepath.getAbsolutePath()+"/TimeLeft/"+FileName);
File outfilepath = Environment.getExternalStorageDirectory();
String FileName = "ExSettings.txt" ;
File outfile = new File(outfilepath, FileName);
Any Ideas?
This is a function that I wrote which will take in a list array and write to a file line by line.
It will use the path in fileName to make a new folder called myfolder in the root of the SDCard, an inside will be your file of newtextfile.txt.
List<String> File_Contents = new ArrayList<String>();
File_Contents.add("This is line one");
File_Contents.add("This is line two");
File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/myfolder/newtextfile.txt");
f.mkDirs();
try {
BufferedWriter out = new BufferedWriter(new FileWriter(f));
for (int x = 0; x < File_Contents.size(); x++) {
out.write(File_Contents.get(x));
out.write(System.getProperty("line.separator"));
}
out.close();
return true;
} catch (Exception e) {
return false;
}
I have a problem with creating a folder and a file on the sdcard.
Here's the code:
File folder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString() + "/folder");
boolean success;
if (!folder.exists()) {
success = folder.mkdirs();
}
File obdt = new File(folder, "file.txt");
try {
success = obdt.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
With this code I expect to create the folderfolder in the Download folder of the sdcard and in this the file file. I want that the user can access the file. So I want to put it in a shared folder.
The success variable is true and when I run the code again the folder already exists and doesnt come in the if-block.
But I can't see the created folder and file on the sdcard in file explorer.
Info:getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString() returns storage/sdcard/Download
I work with a Galaxy Nexus.
Damn! :)
Now I solved my problem...I was misunderstanding the operation of creating files in the file system.
When I spoke of file explorer I meant the file explorer of the operating system and NOT the file explorer in the DDMS :).
I thought when I create a file I will see it in the file explorer of the operating system but when the device is connected to the PC the files can only be seen in the DDMS file explorer.
Sorry I'm new to Android ;)
When the App is running standalone without PC connection and afterwards I connect with the PC I see the created files and folders of course :)
Thanks for help
Any errors from logcat?
Else: try something like Log.I("PATHNAME",folder.absolutePath()); and then look in your logcat to make sure where you are creating the folder where you think it is.
If you haven't done so already, you will need to give your app the correct permission to write to the SD Card by adding the line below to your Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
If you have already done that see if :
File obdt = new File(/sdcard/folder/file.txt)
try {
success = obdt.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
works.
You cannot see the folder/file in explorer? Maybe it is because the MediaScanner is active, but not adding your files. You can do this in your program or switch the Media Scanner of somewhere in your phone settings.
MediaScanner
Trigger MediaScanner
Try this out.
File dir = new File(Environment.getExternalStorageDirectory()
+ "/XXX/Wallpapers/");
File[] files = dir.listFiles();
if (files == null)
{
int numberOfImages = 0;
BitmapDrawable drawable = (BitmapDrawable) imageView
.getDrawable();
Bitmap bitmap = drawable.getBitmap();
File sdCardDirectory = Environment
.getExternalStorageDirectory();
new File(sdCardDirectory + "/XXX/Wallpapers/").mkdirs();
File image = new File(sdCardDirectory
+ "/XXX/Wallpapers/Sample" + numberOfImages + ".JPG");
boolean success = false;
FileOutputStream outStream;
try {
outStream = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (success) {
Toast.makeText(
getApplicationContext(),
"Image saved successfully in Sdcard/XXX/Wallpapers",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Error during image saving", Toast.LENGTH_LONG)
.show();
}
Dont forget to add permission in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Apparently there is a known bug in MTP.
Issue 195362
All phones using MTP instead of USB Mass storage do not properly show the list of files when that phone is connected to a computer using a USB cable. Android apps running on the device also cannot see these files.
It is actually as old as 2012
I've encountered the same problem: created files and folders don't show immediately after being written to sdcard, despite the file being flushed and closed !!
They don't show on your computer over USB or a file explorer on the phone.
I observed three things:
if the absolute path of the file starts with /storage/emulated/0/ it doesn't mean it'll be on your sdcard - it could be on your main storage instead.
if you wait around 5 minutes, the files do begin to show over USB (i.e. Windows explorer and built-in file explorer)
if you use adb shell ls /sdcard from terminal, then the file does show! you could use adb pull ... to get the file immediately. You could probably use DDMS too.
Code I used was:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(myArrayList);
try {
File externalDir = getExternalStorageDirectory();
File newFile = new File(externalDir, "myfile.txt");
FileOutputStream os = new FileOutputStream(newFile);
os.write(json.getBytes());
os.flush();
os.close();
Timber.i("saved file to %s",newFile.getAbsoluteFile().toString());
}catch (Exception ex)
{
Toast.makeText(getApplicationContext(), "Save to private external storage failed. Error message is " + ex.getMessage(), Toast.LENGTH_LONG).show();
}
and
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(myArrayList);
try {
File externalDir = getExternalStorageDirectory();
File newFile = new File(externalDir, "myfile.txt");
FileWriter fw = new FileWriter(newFile);
fw.write(json);
fw.flush();
fw.close();
Timber.i("saved file to %s",newFile.getAbsoluteFile().toString());
}catch (Exception ex)
{
Toast.makeText(getApplicationContext(), "Save to private external storage failed. Error message is " + ex.getMessage(), Toast.LENGTH_LONG).show();
}
why is it like this? Seems like another one of those "Android-isms" that you have to suffer through the first time you experience it.