How can I save a file to external storage with a predefined name for example like myfile_date.mp4?
For external storage we do something like this with basic intelligence..:
private String getFilename()
{
String timeStamp = new SimpleDateFormat("ddMMYYYY").format(new Date());
String MySound = "MySound";
String DefinedName = MySound+timeStamp;
filepath = Environment.getExternalStorageDirectory().getPath();
file = new File(filepath,AUDIO_RECORDER_FOLDER);
if(!file.exists()){
file.mkdirs();
}
return (file.getAbsolutePath() + "/" + DefinedName + file_exts[currentFormat]);
}
Related
I'm able to save a Image in disk using :
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = imageId + ".png";
String filePath = baseDir + File.separator + fileName;
File file = new File(filePath);
if(!file.exists())
{
out = new FileOutputStream(baseDir + File.separator + fileName);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
}
But all the images saved are visible in the gallery of the phone .. How can I hide them to the user ? Is there a private folder for my appliaction ?
Thanks
Save it to the internal storage using Context.getFilesDir() instead of Environment.getExternalStorageDirectory().
From the docs:
Files saved here are accessible by only your app by default.
Check this link out.
public File getAlbumStorageDir(Context context, String albumName) {
// Get the directory for the app's private pictures directory.
File file = new File(context.getExternalFilesDir(
Environment.DIRECTORY_PICTURES), albumName);
if (!file.mkdirs()) {
Log.e(LOG_TAG, "Directory not created");
}
return file;
}
I think this is what you want. Read https://developer.android.com/training/basics/data-storage/files.html#WriteExternalStorage for more information.
I've wrote method below to copy my backup file to external storage
public Boolean Backup() {
try {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
File sd = Environment.getExternalStoragePublicDirectory("");
File data = Environment.getDataDirectory();
String dbPath = "//data//" + "com.example.sqlitetest"
+ "//databases//" + "TestDB";
// Backup file name
Calendar calendar = Calendar.getInstance();
String backupName = calendar.get(Calendar.YEAR) + "-"
+ (calendar.get(Calendar.MONTH) + 1) + "-"
+ calendar.get(Calendar.DAY_OF_MONTH) + "-"
+ calendar.get(Calendar.HOUR_OF_DAY) + ":"
+ calendar.get(Calendar.MINUTE) + ":"
+ calendar.get(Calendar.SECOND);
String backupPath = "//BackupFiles";
File db = new File(data, dbPath);
File backup = new File(sd + backupPath, backupName);
if (!backup.exists())
backup.mkdirs();
FileChannel src = new FileInputStream(db).getChannel();
FileChannel dest = new FileOutputStream(backup).getChannel();
dest.transferFrom(src, 0, src.size());
src.close();
dest.close();
return true;
} else
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
I've added permissions to write and read external storage. The destination folder is created (sd + backupPath) but files no and throws FileNotFoundException! How can I solve this problem?
Thanks in advance
Try:
String dbPath = context.getApplicationInfo().dataDir + File.separator
+ "databases" + File.separator + "TestDB";
And instead of using //, try File.separator.
Your dbPath variable is already a full absolute path name, so can't be used in combination with a File object referring to your data directory, but only on its own. And you got that full path name by making poor assumptions anyway.
What you should do is obtain a File representing the data directory as you are, and use it in combination with a String containing just a filename (within that) and not an absolute directory path.
If you do decide you want directories under your data directory, you can do that, but will have to make sure they exist or create them.
Within my application I am saving data from a game to a .txt file.
I am having the problem at the minute that the String name of the text file is causing the file to be split into two if the game is played over more than a minute.
E.g. if its played over 9.22am and 9.23am then two sperate files are created.
How can I create a more suitable file name, that will be unique for each file.
Code relating to name of text file:
Time t= new Time();
t.setToNow();
int timeFileMinute= t.minute;
int timeFileDate= t.yearDay;
int timeFileYear= t.year;
//creating file name
String fileName= "Maths-" +timeFileMinute + timeFileDate + timeFileYear + android.os.Build.SERIAL;
Full write to file method:
public void writeToFileEEGPower(String data){
Time t= new Time();
t.setToNow();
int timeFileMinute= t.minute;
int timeFileDate= t.yearDay;
int timeFileYear= t.year;
//creating file name
String fileName= "Maths-" +timeFileMinute + timeFileDate + timeFileYear + android.os.Build.SERIAL;
//creating the file where the contents will be written to
File file= new File(dir, fileName + ".txt");
FileOutputStream os;
try{
boolean append= true;
os= new FileOutputStream(file, append);
String writeMe =data + "\n";
os.write(writeMe.getBytes());
os.close();
} catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
EDIT: You should first consider other strategies for generating unique files names like random ones.
You can do it this way:
String fileName = new Date().getTime() + '.txt';
or
String fileName = new SimpleDateFormat("YYYYMMDDhhmmss'.txt'").format(new Date().getTime());
A way to generate file names randomly is:
String name = String.format("%s.txt", RandomStringUtils.randomAlphanumeric(10));
Have a look at this related SO questions:
Current Timestamp as File name in Java
What is the best way to generate a unique and short file name in Java
I need to save file into internal storage, an then read it.
For save it i do something like this:
// Create directory into internal memory;
File mydir = getActivity().getDir("modelli", Context.MODE_PRIVATE);
File a = new File(mydir, obj_id);
a.mkdir();
File b = new File(mydir, obj_id);
if (obj_type != "modello"){
b = new File(a,obj_type);
b.mkdir();
}
String filename = "";
if(obj_imageName != null)
{
filename = obj_imageName + "." + getFileExtension(urlString);
}
else
{
filename = getFileName(urlString);
}
final File file = new File(b, filename);
file.createNewFile();
but I don't know how read it, with this I get an error (contains a path separator):
File mydir = getActivity().getDir("app_modelli/2/images", Context.MODE_PRIVATE);
where is the mistake? is correct my approach for write file?
You better put them in internal files dir. Both for writing and reading you could use a File object like:
String fileName = "info.txt";
File file = new File ( getInternalFilesDir() + "/" + fileName);
At the moment your code only creates a file with length 0. You are not writing/saving anything to it.
dy_path = Environment.getExternalStorageDirectory() + "\5.jpg";
Instead of that i want how to give dynamic path automatically picture saved based on current time.
I am new to Android. Plz answer my question
You could concatenate the path with
DateFormat.getDateInstance().format(new Date());
That is, use something like
String time = DateFormat.getDateInstance().format(new Date());
dy_path = Environment.getExternalStorageDirectory() + "\\" + time + "\\5.jpg";
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/your folder name" + File.separator);
dir.mkdirs();
String pic = CommonMethod.getRandomString(30);
File file = new File(dir, String.valueOf(pic + ".jpg"));
picturePath = picturePath + String.valueOf(pic) + ".jpg";