I am writing an App, in which I would like to append a text file, as various user actions happen. I would like the text file to be located in internal memory. I would like the text file to also be visible under Windows Explorer, if the user connects the tablet with a usb cable.
I have looked at many examples, and have been able to write a text file to internal memory, but I can not seem to make the file visible in File Manager.
Does anyone know if it is possible to write a text file to internal memory, and have it visible to the user under Windows Explorer? Or do I need to use an SD card instead of internal memory?
Ok, I have this working as I want it to, now. It will save the text file (and append it each time it is written) to the non-removable DOWNLOAD folder of a tablet/phone. My target was a minimum SDKversion of 16 (4.1.2 Jellybean).
I will post the code below, for anyone else who gets confused by this issue.
try {
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS);
File myFile = new File(path, "mytextfile.txt");
FileOutputStream fOut = new FileOutputStream(myFile,true);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append("the text I want added to the file");
myOutWriter.close();
fOut.close();
Toast.makeText(this,"Text file Saved !",Toast.LENGTH_LONG).show();
}
catch (java.io.IOException e) {
//do something if an IOException occurs.
Toast.makeText(this,"ERROR - Text could't be
added",Toast.LENGTH_LONG).show();
}
You will also need the following line added to the Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You will need to import:
import java.io.OutputStreamWriter;
import java.io.FileOutputStream;
import java.io.File;
I would like the text file to be located in internal memory.
"Internal memory" does not have a lot of meaning from a programming standpoint.
I would like the text file to also be visible under Windows Explorer, if the user connects the tablet with a usb cable.
That would be external storage.
but I can not seem to make the file visible in File Manager.
Use MediaScannerConnection and its scanFile() method to tell the MediaStore about the file. That will at least allow the file to be visible to an MTP client like Windows' explorer windows. Note that you may need to "refresh" or "reload" in that explorer window to get Windows to pick up the new file.
Related
I was wondering if anyone could possibly help me or give some advice on how to access a text file that has been saved onto an Android phone which is connected to a PC using Unity? Basically I am trying to track a player's heart rate using an Android Wear watch (Huawei Watch 2) and then send that data over to my phone (Huawei P10) which is connected to my PC, where it can hopefully be read by Unity. So far I have been able to collect the heart rate data and send it over to my phone where it is saved into a text file in the external storage (in this case storage/emulated/0). My next step is to read the text file in Unity but I am unsure which is the correct way to do this and searching online has not provided any solid leads and I was hoping someone may be able to point me in the right direction. Apologies if this question is a bit vague and thank you in advance.
First i would get the path of that text file in my logcat
Log.e("PathOfFile",""+filePath);
after i get the path of the file i would go to device monitor in Android Studio, and with my phone connected to pc i will go to storage/emulated/0
Important Note: storage/emulated/0 is located into internal memory, so you are not able to see this text from your phone (if no root was made) , but you can see this file in debug mode from Android Studio
after that you can navigate to your text file
The reason that the file is stored at internal memory might be because you are creating it into internal memory like this
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(fileContents.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
to save it in external storage you should do this
public File getPublicAlbumStorageDir(String albumName) {
// Get the directory for the user's public pictures directory.
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), albumName);
if (!file.mkdirs()) {
Log.e(LOG_TAG, "Directory not created");
}
return file;
}
check the official doc for more info here: https://developer.android.com/training/data-storage/files.html#java
happy coding
Earlier, I was using KitKat on my rooted device, I was able to create temporary files easily. But now I have installed Marshmallow on my Nexus 5, the same code is giving me an exception.
The relevant code is:
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS);
// File repertoireStockage = Environment.getExternalStorageDirectory();
try {
file1 = File.createTempFile("RecordAudio",".mp4", storageDir);
}
catch (IOException e) {
Log.e("RecordAudio", "I/O Problem");
e.printStackTrace();
return;
}
Yes, I do have permissions outside the application tag in Manifest.xml file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Earlier, I used the commented line to get storage directory but now, both are not working. Any kind of help would be appreciated.
I have tried saving file after removing data cable, I still get the same exception.
The OS brings a number of new features and it also has a built-in file manager, which may go unnoticed by many users.
Many third-party file managers allow users to rename files, create new folders, cut files and more. However, Android 6.0 Marshmallow's on-board file manager does not allow such actions.
Be aware that the file paths they return will dynamically change when
the app is moved between internal and external storage devices. When
building file paths, it is strongly recommended that you always call
these APIs dynamically. Don’t use hardcoded file paths or persist
fully-qualified file paths that were built previously.
Link For reference
1) http://developer.android.com/about/versions/marshmallow/android-6.0.html
2) http://www.techtimes.com/articles/94044/20151012/android-6-0-marshmallow-has-a-built-in-file-manager-heres-how-to-access-it.htm
I have an app that needs to collect a bunch of data while connected to a stream. I need to save this data to a file that I can later pull off my device and analyze using a standard computer.
My code currently looks like:
private void saveData(byte[] data){
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File file = new File(path, "_Ascent_Test.txt");
try {
FileOutputStream stream = new FileOutputStream(file, true);
stream.write(data);
stream.close();
Log.i("saveData", "Data Saved");
} catch (IOException e) {
Log.e("SAVE DATA", "Could not write file " + e.getMessage());
}
}
It's correctly hitting the "Data Saved" log without any errors yet I cannot find the file anywhere in the devices internal storage when I browse it from my computer.
What am I missing?
Thanks.
Edit: I'm needed to run this on a Nexus 7
Files are not visible unless you make them explicitly available. See my blog post about the MediaScanner to read more about this.
It's the developer's job to take care of this and to make sure that all files, the user might want to access, are made available to the MediaScanner.
I wanted to do a very similar thing. Here's how I got it to work using your code EXACTLY.
After running my code to make the file(/storage/emulated/0/Download/_Ascent_Test.txt):
I downloaded the ES File Explorer.
In the "Fast Access" menu towards the bottom I turned "Show hidden files" ON.
Then, also in the "Fast Access" menu, go to local -> / Device.
Now you will be able to navigate to the /storage folder and all the way down to _Ascent_test.txt
From there you can open it and email it yourself.
Hope this helped!
So this seems to be a known issue with Nexus 4 and 7. I still don't have a workaround, but for now, using Astro File Manager to email myself will solve the immediate issue at hand.
Saving files on external storage on Nexus 7 and retrieving from PC
Nexus 4 not showing files via MTP
Always fun to waste several hours on something like this. Gah!
I am using
outStream = ctext.openFileOutput("demo.jpg",0);
outStream.write(data);
outStream.close();
If I use the emulator the file is written to the data hieracrchy on the simulated sdcard.
When I run on my Samsung 15500 I cant find where the data has been written to. If I click on MyFiles I can see the directories under Android with a data subdir but no sign of the file.
Am I missing something either in the method of writing the file or the way to find it on the device.
You should be able to find it via Context.getFileList();. The docs to Context.openFileOutput() say
Open a private file associated with this Context's application package for writing
So I guess there is no "guarantee" that you can have arbitrary access to it via file paths or urls or such.
I am trying to save some data from my app in a simple text file on the internal private storage area (app user preferences). I have read through many questions on here (StackOverflow) and tried the solutions suggested with no success. The simplest solution, it seems, would be the one suggested here: http://developer.android.com/guide/topics/data/data-storage.html#filesInternal but I cannot get this to work on my test device. I have also tried to create the file using the methods available in the java.io.File with the appropriate methods. I have also tried to create the file on the SDCard with the same result, fail. I have tried many solutions listed in other answers, following the code and instructions suggested exactly and find the same result. I am beginning to feel that I am missing some important bit of code, or a setting flag somewhere, I have set the permission in the manifest file:
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
To be clear, I am trying to write to the device's internal, private storage. It is a small file containing a name, phone number, and a couple of type int flags. What ever method I use, I either find that the file did not create (or change if I place the file manually on the SDCard), or I get a NullPointerException when I try to reference the file or file location:
private File fILE = new File("Mydata", main.FILENAME);
or
private File fILE = getDir("Mydata", 0);
I am running the code on a HTC Hero, updated with the latest service release from Sprint. Any help would be GREATLY appreciated, Thanks in advance!
-Steve
Update (2/2/11): Using a EVO (API 8) I still get a NullPointerException. The code generating the exception is below, any thoughts on why my app can't access the internal storage? I have this problem on three different physical devices using two API levels (API 7 and 8).
File newfile = new File(this.getFilesDir() + "/data/files/", "sample.txt");
UPDATE 2: 2/4/11 - I have found that I cannot see the file structure on the physical device (data directory) under any circumstance. Any one have any thoughts on this? The device is properly configured and can run app from eclipse or adb.
UPDATE 3: (2/9/11) - I think I may have found what the problem is here, but I am not sure about how to deal with it. I have figured out that the permissions on the /data/ directory on the physical devices are: drwxrwx--x. I am not sure why it is this way, maybe something to with Sprint? I have found this set this way on an HTC Hero, Samsung Epic (Galaxy S), and HTC EVO all on Sprint. The issue appears to be that DDMS and my app do not have r/w access to the directory. I need to figure out 2 things here, why it is like this and how to over come this issue in the wild. Again, any help here would be AWESOME!!
UPDATE 4: I think last February was a total blonde moment for me (see UPDATE 3). The test devices that I have are not ROOTed and hence no access (DUH!). After all the updates that he SGS and the EVO 4G have gone through, the result is still the same. I am still working this problem and will try and get back here with an update soon (hopefully less than a year next time).
Try changing the following line:
File newfile = new File(this.getFilesDir() + "/data/files/", "sample.txt");
to:
File newfile = new File(this.getFilesDir() + "/","sample.txt");
Not a direct answer to your question, but nevertheless: I noticed that you don't want to store tons of data in your file. Would it be a sufficient alternative to use the Shared Preferences instead?
And perhaps even more interesting: does the problem occur even when you write to the Shared Preferences file instead?
http://developer.android.com/guide/topics/data/data-storage.html#pref
A physical device's /data/ directory is only available to the root user. Since the only realistic way to get this access on a physical device is to root the device, DDMS file explorer cannot get into this branch of the directory tree.
As to why the app will not write there, likely the issue is in the fact that I have signed the app with debug keys (not a big *NIX expert, but what appears to be the case here from my personal research).
I was dealing with the same issue. Finally, I found that you really don't have to give all file paths in order to create a new file in internal storage. Just mention the file name and it will be created under your app's package folder at the device. I did exactly mentioned here
And it works perfectly. I would say avoid mentioning Full file path like : /data/... in order to create a file (you need write permissions to create a file in such a manner). Let Android framework do the job for creating a private file for your app.
The internal storage area is sort of private to the application so the user must have root access(rooted device) to create and load the files. If you have rooted device this is how to write a file to the internal storage:
// Create a file in the Internal Storage
String fileName = "MyFile";
String content = "hello world";
FileOutputStream outputStream = null;
try {
outputStream = openFileOutput(fileName, Context.MODE_APPEND);
outputStream.write(content.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
This should instantly create a file called MyFile with the content hello world. The internal storage directory is usually found in a special location specified by our app’s package name. In my case it is /data/data/[package name] and the files created are stored in a directory called files in that directory.
As #bianca says, you're better not using a file path. But instead, use only the filename to create a File. Something like this:
public static void saveTextToFile(Context context, String filename, String content) {
try {
FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
fos.write(content.getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
And to get the file, you can use:
File file = new File(context.getFilesDir(), filename);
Read more: Saving Files.