Save String to a specific folder on internal storage - Android - android

I am basically trying to save a String to a specific folder I create on the internal storage of my phone when I click the button save. I am still a noob at these stuff therefore I do not know what to do. I want to access the file using the file manager and not through the application I created.
So I need help with:
1- Create the folder.
2- Save the string to that specific folder.
Any help is appreciated and thank you in advance.
Save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(getApplicationContext(), ("X values: "+mg1.getXs()) ,Toast.LENGTH_LONG).show();
//Toast.makeText(getApplicationContext(), SENSOR_READING_STRING ,Toast.LENGTH_LONG).show();
String filename = "Data.txt";
String ABCD_STRING = "SENSOR_READING_STRING";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(ABCD_STRING.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
});

By default, when saving to internal storage. The data is private and would only be accessible to the application that saved it. So if you want to be able to open the file through file manager you would need to change this line.
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
Context.MODE_PRIVATE should be either MODE_WORLD_READABLE or MODE_WORLD_WRITEABLE depending on your permission level needed.
More info on openFileOutput flags

Related

Android: Cannot see file saved on external storage

public void write(View view)
{
String state;
File Dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
if (!Dir.exists())
{
Dir.mkdir();
}
File file = new File(Dir,"nahk.txt");
Toast.makeText(getApplicationContext(),file.getAbsolutePath(), Toast.LENGTH_SHORT).show();
String Message = "5nahk";
try {
FileOutputStream FOS = new FileOutputStream(file);
FOS.write(Message.getBytes());
FOS.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I have added write permission in the manifest xml file. This method is called when I press a button. The toast says that the txt file is saved in the Download folder of my Internal Storage (since I don't have an SD card in my LG G3). I open the file location (using FileManager on my LG G3) and there is no "nahk.txt" in that folder. Why can't I see the file?
I'm not familiar with native android development but I encountered something similar using cordova. After saving a file the file was not visible browsing with a usb cable but it was actually there. To see it had to restart my device.
So you could try to restart your device and check if it is still invisible (or create a method which fetches or checks the existence of the saved file to check if it is there).
edit: I learned this by googling so you should find it also
Try this
File Dir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Your_Folder_Name";
File file = new File(Dir,"nahk.txt");
this file will save inside of your device storage Your_Folder_Name

internal storage for app and uri

So I'm using the twitter api and I want to tweet with an image I use:
TweetUri = Uri.fromFile(saveIT);
TweetComposer.Builder builder = new TweetComposer.Builder(this)
.text("")
.image(TweetUri);
builder.show();
The original image is a bitmap, so what I did (not sure if this is the optimal way) was save in the internal storage:
private File saveToInternalStorage(Bitmap bitmapImage){
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
// Create imageDir
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmmss").format(new Date());
String mImageName="MI_"+ timeStamp +".jpg";
File mypath=new File(directory,mImageName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
try
{
fos.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
return mypath;
}
The file it returns will be the "saveIT" in the TweetUri when it does the fromfile method. Of course this will overload the storage so what I plan to do is wipe the internal storage for the app when it is stopped (no other data is saved in the internal storage other than the temp images I save for the tweet):
#Override
protected void onStop() {
super.onStop();
File MSD = this.getApplicationContext().getFilesDir();
File [] lisFiles = MSD.listFiles();
for(int i=0;i<lisFiles.length;i++)
{
boolean deleted = lisFiles[i].delete();
}
}
None of this works... I can't seem to find any of the images when I save them to verify if the deleting is happening. Also, when the user clicks tweet no image is added to the tweet as well. No idea what I'm doing wrong here... In reality I don't want to save the image in the internal storage but I do because the tweet api uses a URI to tweet and not a bitmap.
I switched it to write to external storage and it worked fine. Also I switched it to delete at onDestroy. This is better because, when I invoke the Twitter API it switches activities so the onstop is invoked which would delete the temp picture too early. It's too early becuase if the user clicks cancel at the twitter api, comes back to my api and then invokes the twitter api again the uri will point to nothing since the picture was already deleted. THATS ALL FOLKS :)

java.io.FileNotFoundException Access is denied in Android

I am trying to store my output file in internal memory.but it throws java.io.FileNotFoundException Access is denied
private boolean crop() {
try {
FileOutputStream fos = null;
String filePath = CustomVideoGalleryActivity.videoPath.get(0);
Movie originalMovie = MovieCreator.build(filePath);
Track track = originalMovie.getTracks().get(0);
Movie movie = new Movie();
movie.addTrack(new AppendTrack(new CroppedTrack(track, 200, 800)));
Container out = new DefaultMp4Builder().build(movie);
String outputFilePath = Environment.getDataDirectory()+ "/output_crop.mp4";
fos = new FileOutputStream(new File(outputFilePath)); //throws Exception
out.writeContainer(fos.getChannel());
fos.close();
mProgressDialog.dismiss();
finish();
} catch (Exception e) {
Log.v("ONMESSAGE", e.toString());
e.printStackTrace();
mProgressDialog.dismiss();
return false;
}
return true;
}
You need to ask for write permission in your AndroidManifest.xml. In particular, the following line must be present:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You shouldn't be looking at the Data Directory. This is a system directory in the phone's storage - usually /data - and your application will never have permission to write to it.
The directory your application should write files to is returned by the Context.getFilesDir() method. It will be something like /data/data/com.yourdomain.YourApp/files.
If you want to write to a file in the phone's storage use the Context.openFileOutput() method.
If you want the path to the SDCard then use Environment.getExternalStorageDirectory() method. To write to the SDCard you'll need to give your application the appropriate permissions by adding the following to your Manifest:
If you're going to write to the SDCard you'll also need to check its state with the getExternalStorageState() method.
If you're storing small files to do with your application then these can go into the phone's storage and not the SD Card, so use the Context.openFileOutput() and Context.openFileInput() methods.
So in your code consider something like:
OutputStream os = openFileOutput("samplefile.txt", MODE_PRIVATE);
BufferedWriter lout = new BufferedWriter(new OutputStreamWriter(os));

Open File created by App in internal storage

I'm programming an app that receives all kind of documents as base64 strings. I've been searching all morning, and I didn't find a way to display the documents properly without storing them. As an alternative I wrote this:
private void createReadableFile(DocumentBinary document) {
try {
byte[] bytes = Base64.decode(document.getDocument(), 0);
FileOutputStream os = openFileOutput(document.getSuggestedFileName(), MODE_PRIVATE);
os.write(bytes);
os.flush();
os.close();
openFile(document);
} catch (Exception e) {
Ln.e(e, "Error while parsing document");
}
}
And I do this with the created file:
private void openFile(File file, String mimeType) {
Intent viewIntent = new Intent();
viewIntent.setAction(Intent.ACTION_VIEW);
viewIntent.setDataAndType(Uri.fromFile(file), mimeType);
viewIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(viewIntent);
}
But it doesn't start anything. It calls onPause and onResume but nothing happens. I know that if I change MODE_PRIVATE to MODE_WORLD_READABLE it would work, but MODE_WORLD_READABLE is deprecated. Do you know a better way to do it or what to use instead of MODE_PRIVATE?
Save the file to external storage, or
Use FileProvider to create a ContentProvider that serves the file from internal storage, or
Create your own ContentProvider that implements openFile() and serves up a stream of content from some other source

Android: Possible to write into /etc folder?

I want to know whether it is possible to write data in /etc folder (or any other folder besides data)? If yes, how to do that?
And if not possible, any way to store a permanent data? For scenario example, an app is uninstalled (or clear data), but a specific file will still remain.
thank you.
i'm not sure about /etc folder, but the stuff saved in /data folder is managed by android automatically itself. So when you uninstall an app, anything related to it is also removed from data folder.
However, to store a file permanently besides Data folder on your SdCard, see the code below:
public static boolean saveOnFile(String msg){
boolean saved = false;
String filename = "yourFileName.extension";
try{
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
File root = new File(Environment.getExternalStorageDirectory(), "/YourFolderOnSdCard/");
//create root folders if they do not exist
if(!root.exists()){
root.mkdirs();
}
//now lets save file in our directory structure
File file = new File(root, filename);
FileWriter fw = new FileWriter(file);
fw.append(msg);
fw.flush();
fw.close();
saved = true;
}
else
Log.e("Save", "Mounted media is not available or is write-protected");
}
catch (Exception e) { Log.e("Save", e.toString()); }
return saved;
}
This Data Storage guide could be useful.

Categories

Resources