public void onClick(View v) {
// Writing data to file
FileWriter fw;
try {
fw = new FileWriter(Environment.getExternalStorageDirectory()+"/DataLog.csv", true);
BufferedWriter br = new BufferedWriter(fw);
br.append(formattedDate + String.valueOf(location.getLatitude()) +
";" + String.valueOf(location.getLongitude()) +
";" + String.valueOf(location.getSpeed()) +
";" + String.valueOf(location.getBearing()) +
";" + String.valueOf(location.getAltitude()) +
";" + String.valueOf(location.getAccuracy()));
br.append("\r\n");
br.close();
fw.close();
// MediaScanner scans the file
MediaScannerConnection.scanFile(MainActivity.this, new String[] {fw.toString()} , null, new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
Toast t = Toast.makeText(MainActivity.this, "Scan comlete", Toast.LENGTH_LONG);
t.show();
}
} );
} catch (IOException e) {
e.printStackTrace();
}
}
I tried a code to write data to a DataLog.csv file in the sd root. The code creates the file with the data but i cannot see the file in windows when browsing the sdcard.
I saw this video and followed the instructions but it is not working for me. Maybe the fw variable is not good to define the file?
File csv = new File (Environment.getExternalStorageDirectory(), "DataLog.csv");
MediaScannerConnection.scanFile(
MainActivity.this,
new String[] {csv.getAbsolutePath()},
null, null);
I tried your advice like this but it still doing nothing.
toString() on FileWriter does not return the path to the file, which you are assuming it does, in the second parameter you pass to scanFile().
Related
I am trying to delete image from device by using file.delete(). Delete method is being called and even it is returning true but when I open my gallery image is still there.
My image path is :
/data/user/0/com.myappname/app_myappname/20180413__164222_0.7680390806195996.png
Please have a look what i have tried.
1)
File file = new File(path);
if (file.exists()) {
file.delete();
}
2)
try {
File file = new File("file://" + path);
String getDirectoryPath = file.getParent(); // Only return path if physical file exist else return null
File fileNew = new File(getDirectoryPath);
fileNew.delete();
} catch (Exception e) {
}
3)
File file = mContext.getFilesDir(); // this will get you internal directory path
Log.d("BLA BLA", file.getAbsolutePath());
File newfile = new File(file.getAbsolutePath() + imagePath); // foo is the directory 2 create
newfile.delete();
4)
try
{
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
File fileName = new File(data, imagePath);
if (fileName.exists())
{
fileName.delete();
}
}
} catch (Exception e) {
}
I have applied almost every solution from stack overflow related to file.delete(). But nothing is working ? Any help or clue will be appreciated.
Edit:
I have refreshed the gallery when delete() returns true using this method but still image is present in app gallery.
Look at my code:
public void callBroadCast() {
if (Build.VERSION.SDK_INT >= 14) {
Log.e("-->", " >= 14");
MediaScannerConnection.scanFile(mContext, new String[]{Environment.getExternalStorageDirectory().toString()}, null, new MediaScannerConnection.OnScanCompletedListener() {
/*
* (non-Javadoc)
* #see android.media.MediaScannerConnection.OnScanCompletedListener#onScanCompleted(java.lang.String, android.net.Uri)
*/
public void onScanCompleted(String path, Uri uri) {
Log.e("ExternalStorage", "Scanned " + path + ":");
Log.e("ExternalStorage", "-> uri=" + uri);
}
});
} else {
Log.e("-->", " < 14");
mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}
}
I want to write something to a file. I found this code:
private void writeToFile(String data) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("config.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
The code seems very logical, but I can't find the config.txt file in my phone.
How can I retrieve that file which includes the string?
Not having specified a path, your file will be saved in your app space (/data/data/your.app.name/).
Therefore, you better save your file onto an external storage (which is not necessarily the SD card, it can be the default storage).
You might want to dig into the subject, by reading the official docs
In synthesis:
Add this permission to your Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
It includes the READ permission, so no need to specify it too.
Save the file in a location you specify (this is taken from my live cod, so I'm sure it works):
public void writeToFile(String data)
{
// Get the directory for the user's public pictures directory.
final File path =
Environment.getExternalStoragePublicDirectory
(
//Environment.DIRECTORY_PICTURES
Environment.DIRECTORY_DCIM + "/YourFolder/"
);
// Make sure the path directory exists.
if(!path.exists())
{
// Make it, if it doesn't exit
path.mkdirs();
}
final File file = new File(path, "config.txt");
// Save your stream, don't forget to flush() it before closing it.
try
{
file.createNewFile();
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(data);
myOutWriter.close();
fOut.flush();
fOut.close();
}
catch (IOException e)
{
Log.e("Exception", "File write failed: " + e.toString());
}
}
[EDIT] OK Try like this (different path - a folder on the external storage):
String path =
Environment.getExternalStorageDirectory() + File.separator + "yourFolder";
// Create the folder.
File folder = new File(path);
folder.mkdirs();
// Create the file.
File file = new File(folder, "config.txt");
Write one text file simplified:
private void writeToFile(String content) {
try {
File file = new File(Environment.getExternalStorageDirectory() + "/test.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter writer = new FileWriter(file);
writer.append(content);
writer.flush();
writer.close();
} catch (IOException e) {
}
}
This Method takes File name & data String as Input and dumps them in a folder on SD card.
You can change Name of the folder if you want.
The return type is Boolean depending upon Success or failure of the FileOperation.
Important Note: Try to do it in Async Task as FIle IO make cause ANR on Main Thread.
public boolean writeToFile(String dataToWrite, String fileName) {
String directoryPath =
Environment.getExternalStorageDirectory()
+ File.separator
+ "LOGS"
+ File.separator;
Log.d(TAG, "Dumping " + fileName +" At : "+directoryPath);
// Create the fileDirectory.
File fileDirectory = new File(directoryPath);
// Make sure the directoryPath directory exists.
if (!fileDirectory.exists()) {
// Make it, if it doesn't exist
if (fileDirectory.mkdirs()) {
// Created DIR
Log.i(TAG, "Log Directory Created Trying to Dump Logs");
} else {
// FAILED
Log.e(TAG, "Error: Failed to Create Log Directory");
return false;
}
} else {
Log.i(TAG, "Log Directory Exist Trying to Dump Logs");
}
try {
// Create FIle Objec which I need to write
File fileToWrite = new File(directoryPath, fileName + ".txt");
// ry to create FIle on card
if (fileToWrite.createNewFile()) {
//Create a stream to file path
FileOutputStream outPutStream = new FileOutputStream(fileToWrite);
//Create Writer to write STream to file Path
OutputStreamWriter outPutStreamWriter = new OutputStreamWriter(outPutStream);
// Stream Byte Data to the file
outPutStreamWriter.append(dataToWrite);
//Close Writer
outPutStreamWriter.close();
//Clear Stream
outPutStream.flush();
//Terminate STream
outPutStream.close();
return true;
} else {
Log.e(TAG, "Error: Failed to Create Log File");
return false;
}
} catch (IOException e) {
Log.e("Exception", "Error: File write failed: " + e.toString());
e.fillInStackTrace();
return false;
}
}
You can write complete data in logData in File
The File will be create in Downlaods Directory
This is only for Api 28 and lower .
This will not work on Api 29 and higer
#TargetApi(Build.VERSION_CODES.P)
public static File createPrivateFile(String logData) {
String fileName = "/Abc.txt";
File directory = new File(Environment.getExternalStorageDirectory() + "/" + Environment.DIRECTORY_DOWNLOADS + "/");
directory.mkdir();
File file = new File(directory + fileName);
FileOutputStream fos = null;
try {
if (file.exists()) {
file.delete();
}
file = new File(getAppDir() + fileName);
file.createNewFile();
fos = new FileOutputStream(file);
fos.write(logData.getBytes());
fos.flush();
fos.close();
return file;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
I have been looking at the forum and found some tips but none of them bring me to the final solution. I need the code if possible, please.
I am creating a txt file every time I close my app and what I am aiming for is to rename the file in case it already exists with the following format:
file.txt - file(1).txt - file(2).txt
Up until now what I get is the following:
file.txt - file.txt1 - file.txt12
The code that I have is the following:
int num = 0;
public void createFile(String name) {
try {
String filename = name;
File myFile = new File(Environment.getExternalStorageDirectory(), filename);
if (!myFile.exists()) {
myFile.createNewFile();
} else {
num++;
createFile(filename + (num));
}
} catch (IOException e) {
e.printStackTrace();
}
}
Thanks everybody in advance!
Your filename variable contains the whole name of your file (i.e. file.txt). So when you do this:
createFile(filename + (num));
It simply adds the number at the end of the file name.
You should do something like this:
int num = 0;
public void createFile(String prefix) {
try {
String filename = prefix + "(" + num + ").txt"; //create the correct filename
File myFile = new File(Environment.getExternalStorageDirectory(), filename);
if (!myFile.exists()) {
myFile.createNewFile();
} else {
num++; //increase the file index
createFile(prefix); //simply call this method again with the same prefix
}
} catch (IOException e) {
e.printStackTrace();
}
}
Then just call it like this:
createFile("file");
I used this code below to save an image taken from the camera intent, to a folder in the gallery, which worked great. I'd like to retrieve the image to display on an ImageView within an activity when asked, though after trying various methods/code, nothing so far has worked. Given the path/code used to save the image, could someone point me in the right direction of how to get it back. Thanks in advance - Jim.
public void SaveImage(Context context,Bitmap ImageToSave, String fileName){
TheThis = context;
String file_path = Environment.getExternalStorageDirectory()+ NameOfFolder;
// String CurrentDateAndTime= getCurrentDateAndTime();
File dir = new File(file_path);
if(!dir.exists()){
dir.mkdirs();
}
File file = new File(dir, fileName + ".jpg");
try {
FileOutputStream fOut = new FileOutputStream(file);
ImageToSave.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.flush();
fOut.close();
MakeSureFileWasCreatedThenMakeAvabile(file);
AbleToSave();
}
catch (FileNotFoundException e) {UnableToSave();}
catch (IOException e){UnableToSave();}
}
private void MakeSureFileWasCreatedThenMakeAvabile(File file) {
MediaScannerConnection.scanFile(TheThis,
new String[] { file.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.e("ExternalStorage", "Scanned " + path + ":");
Log.e("ExternalStorage", "-> uri=" + uri);
}
});
}
If you have a proper path and permissions, here is the code working perfectly for me
File rootsd = Environment.getExternalStorageDirectory();
String rootPath = rootsd.getAbsolutePath();
String pathName = rootPath + "your path here" + "image name here";
try {
Drawable d = Drawable.createFromPath(pathName);
layout.setBackgroundDrawable(d);
} catch (Exception e) {
e.printStackTrace();
}
Hope this helps and enjoy your work.
I have a database table, my goal is to read in each of the values from the data table, then write them to a text file to be emailed. How should I go about accomplishing this?
public void FileWrite()
{
Cursor remindersCursor = mDbHelper.fetchAllReminders();
startManagingCursor(remindersCursor);
try
{ // catches IOException below
String[] from = new String[]{RemindersDbAdapter.KEY_TITLE};
final String TESTSTRING = new String(RemindersDbAdapter.KEY_TITLE + " ");
File sdCard = Environment.getExternalStorageDirectory();
File myFile = new File(sdCard, "test");
FileWriter writer = new FileWriter(myFile);
writer.append(TESTSTRING);
writer.flush();
writer.close();
Toast.makeText(TaskReminderActivity.this, "Program Successfully went through FileWrite!", Toast.LENGTH_LONG).show();
} catch(Exception e)
{
Toast.makeText(TaskReminderActivity.this, "Had Problems with file!", Toast.LENGTH_LONG).show();
Log.e("FileWrite", "Had Problems with file!", e);
}
}
First Reading from you sqllite Database :
Cursor cursor = db.rawQuery("SELECT * FROM " +TBL_NAME+" " ,null);
startManagingCursor(cursor);
while(cursor.moveToNext()){
stringBuffer.append(cursor.getString(1)).append(";");
}
......
Next Writing on the card :
try {
File myFile = new File("/sdcard/file.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(stringBuffer.toString());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Done writing SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
....
Make sure you have permission set in your manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Just a simple example. Hope you can pick up easily
http://android-er.blogspot.in/2011/06/simple-example-using-androids-sqlite_02.html