Reputation: 33
is there a method that allows in Android 2.1 to create a new file and, if relative directories do not exist, to create them too? make me know, 'cause this snippet does not work:
static String separator = File.separator;
public static final String DIRECTORYBIGLIETTI = "C:" + separator + "Users" + separator + "7-Spode" + separator + "Documents" + separator + "Android" + separator + "HUVWSZE"; ///sdcard/.SpodeApps/HUVWSZE/
public static final String FILEBIGLIETTI = DIRECTORYBIGLIETTI.concat(separator + "lista.txt");
File cartellainputoutput = new File(DIRECTORYBIGLIETTI);
if(!cartellainputoutput.exists())
{
cartellainputoutput.mkdirs();
}
File fileinputoutput = new File(FILEBIGLIETTI);
if(!fileinputoutput.exists())
try {
fileinputoutput.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
may i ask to the admin for upgrading this web site's graphics? ;)
Upvotes: 1
Views: 1191
Reputation: 40884
Just to make this clear, you cannot use Windows-like file paths (such as C:\Users\7-Spode\Documents\Android\HUVWSZE
) in Android, you have to use Linux-like file paths (like /data/my.android.application/data_directory/file
or /sdcard/directory/file
.
Also, you should use methods such as getFilesDir()
(for internal storage) and getExternalStorageDirectory()
(for external storage, e.g. SD cards) to get those directories, and from there you can just create a regular File
object and handle it from there.
Example (with internal storage):
File dir = getFilesDir(); // Returns a directory exclusively for this app.
File file = new File(dir, "directory/file");
file.mkdirs();
file.createNewFile();
Also note that when working with external storage, you should always check if external storage is unavailable (for instance if SD card has been removed, or the device is connected
to a computer), using getExternalStorageState()
.
For more information about how to use internal and external storage in Android, read this nifty article.
Upvotes: 1
Reputation:
You need to use mkdirs()
to create the directories, and then create the file.
Upvotes: 2