I have following question. I'd like to place a file named data.xml into sdcard/appname folder and use it for read and write application data.
So, when my main activity creates I need to check if this file exist:
public class appname extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.no_elements_l);
File file = getBaseContext().getFileStreamPath("/sdcard/appname/data.xml");
if(file.exists()) {
return;
} else {
// create a File object for the parent directory
File MTdirectory = new File("/sdcard/appname/");
// have the object build the directory structure, if needed.
MTdirectory.mkdirs();
// create a File object for the output file
File outputFile = new File(MTdirectory, "data.xml");
// now attach the OutputStream to the file object, instead of a String representation
FileOutputStream DataFile = new FileOutputStream(outputFile);
}
But I have Unhandled exception type FileNotFoundException in last line. What's the problem? Uses permission WRITE_EXTERNAL_STORAGE is added to manifest.
Don't hardcode SDCard file path. It can be different for different devices and APIs.
For example it's /mnt/sdcard/ for Froyo while that of my Galaxy Nexus (JellyBean) is /storage/sdcard0/
Android Developer's Guide recommends using Environment.getExternalStorageDirectory()
Try doing it like this:
// Some Code
String path = Environment.getExternalStorageDirectory().getPath() + "/appname/";
File file = getBaseContext().getFileStreamPath(path);
// More Code
Does the path '/sdcard/appname' exist? You check for the file before you check for the sub-directory 'appname'. You need to check if that exists before you try to access a file inside it.
Also if you simply need the file to read-write application data why not just go with internal storage - one less manifest permission :) -> read here for internal storage
Related
I have a list of arrays of data in my app that I would now like to write to a file (csv) and use a 3rd party app (such as email) to share this csv file. I have had no luck finding any helpful resources for creating, finding the file path for, and appending to a file in Kotlin. Does anyone have experience with this or have examples to point to? Just to get started I'm trying to write the header and close the file so I can see that it is correctly writing.
This is what I have for now:
val HEADER = "ID, time, PSI1, PSI2, PSI3, speed1, speed2, temp1, temp2"
val filename = "export.csv"
var fileOutStream : FileOutputStream = openFileOutput(filename,Context.MODE_PRIVATE)
try {
fileOutStream.write(HEADER.toByteArray())
fileOutStream.close()
}catch(e: Exception){
Log.i("TAG", e.toString())
}
It doesn't throw the exception, but I cannot find the file in the file system. I'm using a physical tablet for testing/debug. I've checked the com.... folder for my app.
I cannot find the file in the file system
Use Android Studio's Device File Explorer and look in /data/data/.../files/, where ... is your application ID.
Also, you can write your code a bit more concisely as:
try {
PrintWriter(openFileOutput(filename,Context.MODE_PRIVATE)).use {
it.println(HEADER)
}
} catch(e: Exception) {
Log.e("TAG", e.toString())
}
use() will automatically close the PrintWriter, and PrintWriter gives you a more natural API for writing out text.
It appears there are many ways to create a file and append to it, depending on the minimum API version you are developing for. I am using minimum Android API 22. The code to create/append a file is below:
val HEADER = "DATE,NAME,AMOUNT_DUE,AMOUNT_PAID"
var filename = "export.csv"
var path = getExternalFilesDir(null) //get file directory for this package
//(Android/data/.../files | ... is your app package)
//create fileOut object
var fileOut = File(path, filename)
//delete any file object with path and filename that already exists
fileOut.delete()
//create a new file
fileOut.createNewFile()
//append the header and a newline
fileOut.appendText(HEADER)
fileOut.appendText("\n")
/*
write other data to file
*/
openFileOutput() creates a private file, likely inside of app storage. These files are not browsable by default. If you want to create a file that can be browsed to, you'll need the WRITE_EXTERNAL_STORAGE permission, and will want to create files into a directory such as is provided by getExternalFilesDir()
I am trying to use Android's internal helpers to get a path from the system for my file first and then put my files where the system wants. Because tomorrow they might change their minds.
I made a simple program to explore this subject. Here is my code;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String path = letsMakeAfile(this, "myFile.txt");
}
private static String letsMakeAfile(Context context, String nameOfFile) {
String strOfFinalPath ="";
//ask the system what path to use...
String strOfContextPath = context.getFilesDir() + "/";
//line above doesnt work without ' + "/" ' or something on the end
//line above records this path: /data/user/0/com.example.filesexperimenting/files/
//this appears to be an invalid path unless "user" is a hidden directory
Log.d("IDIOT", "strOfContextPath: "+ strOfContextPath);
try
{
File file = new File(strOfContextPath, nameOfFile);
if (file.exists() == false) {
file.mkdirs();
//after this line "makes dirs" is file automatically still made and dropped in?
letsMakeAfile(context, nameOfFile);
//I assume not so Ive made a recursive call
}
else
;
//escape recursion....
strOfFinalPath = file.getAbsolutePath();
//Here I record the path where I hope the file is located
Log.d("IDIOT", "strOfFinalPath: "+ strOfFinalPath);
}
catch (Exception e) {
e.printStackTrace();
Log.d("IDIOT", "CATCH ERROR: "+ e.getLocalizedMessage());
}
//runs without a catch
return strOfFinalPath;
}
}
Logcat:
2019-04-09 09:59:22.901 16819-16819/? D/IDIOT: strOfContextPath: /data/user/0/com.example.filesexperimenting/files/
2019-04-09 09:59:22.901 16819-16819/? D/IDIOT: strOfFinalPath: /data/user/0/com.example.filesexperimenting/files
Ultimately I am getting a path of /data/user/0/com.example.filesexperimenting/files/ from context.getFilesDir() which appears to be an invalid path unless "user" is a hidden directory (then why can I see root?). In Device File Explorer under data the only other directories are app, data and local
What am I missing? I'll assume its something with file.makedirs()
Full disclosure, I am a student and there is not a lot out there on this so your replies, while obvious to you at your experience level, should help others. I have some experience with Java and more with C++ but Android is new to me. Thanks in advance!
So, in talking outside of StackExchange it appears that using java.io like I am trying to in the example can cause some problems because of the preset file directories that may be locked or restricted that Java io might not know about.
Android has it's own method openFileOutput(String name, int mode) that has the ability to create the app resource file and directory it belongs in.
Description copied from class: android.content.Context
Actions:
~Open a private file associated with this Context's application package for writing.
~Creates the file if it doesn't already exist.
~No additional permissions are required for the calling app to read or write the returned file.
Params:
~name – The name of the file to open; can not contain path separators.
~mode – Operating mode.
Returns: The resulting FileOutputStream.
Throws: java.io.FileNotFoundException
If you want to be able to navigate to the location of your saved files through the file explorer (either in Android Studio or the Files app on the phone) you should use Context.getExternalFilesDir().
Context.getFilesDir() returns a directory not accessible by anyone BUT the creating application. So if you would like to see what is in this file you would need to open it with the same application that wrote it. IE: Print the contents to the screen after you save it in your app.
Context.getExternalFilesDir() returns a directory completely accessible by anyone and any application. So files created and saved in this external directory can be seen by Android Studio's file explorer as the OP has screenshot or by any application installed on the phone.
What is nice about both of these methods is that as long as you are only accessing files you have created you never need to ask the user for storage permissions Read or Write. If you would like to write to someone else's external files dir then you do.
Source
Check if sdcard is mounted or not.
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)){
///mounted
}
Get the path of sd card
File dir= new File(android.os.Environment.getExternalStorageDirectory());
walkdir(dir);
ArrayList<String> filepath= new ArrayList<String>();
//list for storing all file paths
public void walkdir(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
// if its a directory need to get the files under that directory
walkdir(listFile[i]);
} else {
// add path of files to your arraylist for later use
//Do what ever u want
filepath.add( listFile[i].getAbsolutePath());
}
}
}
}
Try using this:
context.getFilesDir().getParentFile().getPath()
I have a Samsung Galaxy S6. I'm currently working on a test application where I would like quick access to a folder with my files.
Using the provided "My Files" Application, it specifies that all those folders are in the "Internal Storage" folder.
I know that internal storage is private, but I want to create a folder in the default folder that windows accesses when the phone is plugged in.
For example, the following code does not create the directory in the correct location.
File storage = new File("/testappplication");
if(!storage.exists()) {
storage.mkdir();
System.out.println("Folder Created");
}
I just want to know the path where to create the folder. Many other applications have storage here, so I know its possible.
You can't create a directory inside the internal storage of the device. Except you've a root access for the app.
So, the following code won't work:
File storage = new File("/testappplication");
Because it tell the app to create a testappplication in the root folder.
You can only create the directory inside your app private folder within the following path:
String path = getFilesDir().getAbsolutePath();
And make the folder using the path.
Or you can use something like this:
File folder = new File(context.getFilesDir(), "testappplication");
if (!folder.exists()) {
folder.mkdirs();
} else {
// folder is exist.
}
Read more at Saving Files
First just for trial make runtime permmision and then try the following code
private void createInternalFile() {
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()+"/"+getApplicationContext()
.getPackageName()+"/File/profile");
if (!mediaStorageDir.exists()) {
mediaStorageDir.mkdirs();
} }
then check your internal storage in which you will find a folder whose name is your package name
After a while later I found the answer to this question.
public void createDirectory() {
File file = new File(Environment.getExternalStorageDirectory(), "/test");
if (!file.exists()) {
file.mkdirs();
Log.w("DEBUG", "Created default directory.");
}
}
This is how you create it code wise. The reason it wasn't creating was due to Samsungs weird permissions.
Make sure you have the storage permission enabled in Settings -> Apps -> App Name -> Permissions. I needed to turn it on so it would create the folder.
In Android, I want to create a pointer that points to already existing file by way of its filepath.
For example, my pseudo-code:
String path = "file/directory/filename";
File ptr = File's pointed to by the path
The Android documentation only provides methods with which one can create a new file through a file path, but I just want a File object that only points to an already existing File.
How do I do that?
Use:
String path = "file/directory/filename";
File ptr = new File(path);
// check If file exists.
if(ptr.exists()) {
// Your code Here if file exists
}
File f = new File(path);
f points to a virtual file , if the file doesnt exist, writing anything to it, will either create it or cause a system crash , depending on the type of content you are writing to it.
deleting a file that doesnt exist will also fail, so any operation with files must be encapsulated with try catch for IOException
see http://developer.android.com/reference/java/io/File.html
also on android's new Kitkat you explicity have to request the permission to READ_EXTRANL_STORAGE if you want to read, and WRITE_EXTERNAL_STORAGE if you want to write
in my app I am seeing few crashes when I try to create a directory structure under the application internal storage, such as /data/data/[pkgname]/x/y/z....
Here is the failing code:
File clusterDirectory = new File(MyApplication.getContext().getFilesDir(), "store");
File baseDirectory = new File(clusterDirectory, "data");
if (!baseDirectory.exists()) {
if (!baseDirectory.mkdirs()) {
throw new RuntimeException("Can't create the directory: " + baseDirectory);
}
}
My code is throwing the exception when trying to create the following path:
java.lang.RuntimeException: Can't create the directory: /data/data/my.app.pkgname/files/store/data
My manifest specifies the permission <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />, even if it should not be necessary for this purpose (it is actually necessary for my apps due to Google Maps Android API v2).
It doesn't seem to be related to the phone, since I get this exception on old phones as well as on new ones (last crash report is Nexus 4 with Android 4.3).
My guess is that the directory /data/data/my.app.pkgname doesn't exist in the first place but mkdirs() can't create it because of permissions issues, could that be possible?
Any hints?
Thanks
Use getDir(String name, int mode) to create directory into internal memory. The method Retrieve, creating if needed, a new directory in which the application can place its own custom data files. You can use the returned File object to create and access files in this directory.
So example is
// Create directory into internal memory;
File mydir = context.getDir("mydir", Context.MODE_PRIVATE);
// Get a file myfile within the dir mydir.
File fileWithinMyDir = new File(mydir, "myfile");
// Use the stream as usual to write into the file.
FileOutputStream out = new FileOutputStream(fileWithinMyDir);
For nested directories, you should use normal java method. Like
new File(parentDir, "childDir").mkdir();
So updated example should be
// Create directory into internal memory;
File mydir = getDir("mydir", Context.MODE_PRIVATE);
// Create sub-directory mysubdir
File mySubDir = new File(mydir, "mysubdir");
mySubDir.mkdir();
// Get a file myfile within the dir mySubDir.
File fileWithinMyDir = new File(mySubDir, "myfile");
// Use the stream as usual to write into the file.
FileOutputStream out = new FileOutputStream(fileWithinMyDir);