Create a file on Android Internal Storage? - android

I'm trying to write a text file in android's internal storage and browse through connecting it to a PC via usb. Now, I used the following code which worked fine for old devices with SD cards.
public void writeToFile(String stringToBeWritten)
{
final File path =
Environment.getExternalStoragePublicDirectory
(
Environment.DIRECTORY_DCIM + "/Target Folder/"
);
if(!path.exists())
{
path.mkdirs();
}
final File file = new File(path, "MyFile.txt");
try
{
file.createNewFile();
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(stringToBeWritten);
System.out.println("Written Successfully");
myOutWriter.close();
fOut.flush();
fOut.close();
}
catch (IOException e)
{
Log.e("Exception", "File write failed: " + e.toString());
}
}
I've been surfing for a solution a while and tried a lot of thing to get my job done. All the solutions out there, to store the file internally but unable to browse.
Any ideas how to write my files on internal phone storage? I'd highly appreciate any help/suggestions. Thanks.

Related

Android Append text to file not working even if fileOutputStream appending mode setted to TRUE

I am trying to append text into a file stored in emulated/0/.. folder (external storage without SD Card)
FileOutputStream fileOutputStream = new FileOutputStream(capturesFile, true);
OutputStreamWriter writer = new OutputStreamWriter(fileOutputStream);
String data = "my data";
writer.append(data);
writer.close();
fileOutputStream.flush();
fileOutputStream.close();
This code is not working, I really do not understand why. Is the emulated location is a problem (stupid question but at this point...) I already tried many ways without any positive solution.
Is someone have an idea about this issue.
Use this code
try {
FileWriter fw = new FileWriter("path/of/file",true);
fw.write("myData");
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
First make sure you've given the required permission to write a file and that would be -
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
in Manifest file and
if (ContextCompat.checkSelfPermission(context,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_EXT_STORAGE);
}
in your activity.
Second please check your directory path. There might be some chances that you are using a wrong path. Easiest way to get a direct path for the Internal Storage is -
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data" + getApplicationContext().getPackageName();
File file = new File(path + "/File.txt");
You can use this method as per your requirement to write a file -
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(file));
outputStreamWriter.append("My Data");
outputStreamWriter.flush();
outputStreamWriter.close();
} catch (IOException e) {
e.printStackTrace();
}

file size not showing correct in android

I am using print writer and fileoutputstream to write a file in android async task using following function:
public static void saveFileToExternalMemoryAsync(Context context,String fileName, String json)throws Exception{
File AppPath = new File(Environment.getExternalStorageDirectory() + "/PDMA/DMAPPOutputs/");
if (!AppPath.exists()) {
AppPath.mkdirs();
}
File outputFile = new File(AppPath.getAbsolutePath() + "/" + fileName + ".dmapp");
if (!outputFile.exists())
outputFile.createNewFile();
MediaScannerConnection.scanFile(context, new String[] {AppPath.toString(),outputFile.toString()}, null, null);
FileOutputStream fileOutputStream = new FileOutputStream(outputFile, true);
PrintWriter pw = new PrintWriter(fileOutputStream);
try{
pw.println(json);
pw.flush();
pw.close();
fileOutputStream.flush();
fileOutputStream.close();
}catch (Exception e){
e.printStackTrace();
}finally{
pw.flush();
pw.close();
fileOutputStream.flush();
fileOutputStream.close();
MediaScannerConnection.scanFile(context, new String[] {AppPath.toString(),outputFile.toString()}, null, null);
}
}
problem is that when I try to copy this file by connecting mobile to pc in mtp, its not copied fully. If I right click to see its size, its less than actual. Now If in android, I copy and paste this file somewhere else, say in downloads folder, size is correct and file is also complete.
What can be the problem.
UPDATE:
If I use fileOutputStream to write bytes one by one , then file is generated but I have to close application to access this file from pc.
Well it turns out that by adding this.cancel(true) at the end of onPostExecute() solved problem in my case.

Issue on appending a file in android

I am creating an android application which reads and writes data to a file in the location /sdcard/ReadandWrite/.when i writing to that file it does not write in append mode.it will removes the old data and writes the new one.please help me to solve this.Here is my code.
private File openfile() {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/ReadandWrite");
dir.mkdirs();
File file = new File(dir, "myfile.txt");
file.setWritable(true);
if(file.exists())
{
file.canRead();
file.setWritable(true);
}
else {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
return file;
}
private void writetofile() {
try {
File file=openfile();
OutputStreamWriter myOutWriter =
new OutputStreamWriter(new FileOutputStream(file));
myOutWriter.append(text.getText());
myOutWriter.close();
myOutWriter.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();
}
You need to configure the FileOutputStream to use append mode. From JDK documentation:
public FileOutputStream(String name,
boolean append)
throws FileNotFoundException
Creates a file output stream to write to the file with the specified
name. If the second argument is true, then bytes will be written to
the end of the file rather than the beginning. A new FileDescriptor
object is created to represent this file connection.
First, if there is a security manager, its checkWrite method is called
with name as its argument.
If the file exists but is a directory rather than a regular file, does
not exist but cannot be created, or cannot be opened for any other
reason then a FileNotFoundException is thrown.
Parameters:
name - the system-dependent file name
append - if true, then bytes will be written to the end of the file rather than the beginning Throws:
FileNotFoundException - if the file exists but is a directory rather than a regular file, does not exist but cannot be created, or
cannot be opened for any other reason.
SecurityException - if a security manager exists and its checkWrite method denies write access to the file. Since:
JDK1.1 See Also:
SecurityManager.checkWrite(java.lang.String)
So change
OutputStreamWriter myOutWriter = new OutputStreamWriter(new FileOutputStream(file));
to
OutputStreamWriter myOutWriter = new OutputStreamWriter(new FileOutputStream(file, true));

Saved Bitmap doesn't appear on SD Card

I am working on an app in which I would like to save some Bitmaps to the SD Card. I have looked at a lot of examples and other questions, and from that I have made the following code:
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
String dirPath = Environment.getExternalStorageDirectory().toString() + "/myFolder";
File dir = new File(dirPath);
dir.mkdirs();
String fileName = "bitmapname.jpg";
File file = new File(dirPath, fileName);
FileOutputStream fileOutPutStream;
try {
boolean created = file.createNewFile();
Log.d("Checks", "File created: " + created);
fileOutPutStream = new FileOutputStream(file);
fileOutPutStream.write(byteArrayOutputStream.toByteArray());
fileOutPutStream.close();
} catch (FileNotFoundException e) {
Log.d("Checks", "FileNotFoundException");
e.printStackTrace();
} catch (IOException e) {
Log.d("Checks", "IOException");
Log.d("Checks", e.getMessage());
e.printStackTrace();
}
I don't see what's wrong with this code. It doesn't give any errors and my app runs without crashing. However, when I connect my phone to my computer and open the SD Card I do not see the folder "myFolder" and I can not find the saved image anywhere. Do you guys have any ideas as to why this is?
EDIT: I noticed that I can see the saved bitmaps in the Android gallery, and they are indeed in a folder called "myFolder". However, I still don't see them when I connect my phone to my computer and browse my sd card.
From my experience I had similar issued when I forgot the fileOutPutStream.flush(); before the close().
Are you sure you are setting the permission to write to SD card? Try setting this one:
WRITE_EXTERNAL_STORAGE
Edit:
Ok, try this:
Environment.getExternalStorageDirectory().getAbsolutePath()
Instead of:
Environment.getExternalStorageDirectory().toString()
Or even create a directory like this:
File dir = new File(Environment.getExternalStorageDirectory() +
File.separator +
"myFolder");
dir.mkdirs();

How to save file without SD Card?

I have a device without a memory card and I want to save the file. I've tried:
filePath = Environment.getDataDirectory().toString();
/data/.... EACCES (Permission denied)
filePath = Environment.getDownloadCacheDirectory().toString();
/cache/.... EACCES (Permission denied)
and
filePath = Environment.getRootDirectory().toString();
/system/.... EROFS (Read-only file system)
is there other way?? (Sorry for my english :P)
Try to write file into internal storage, in your apps local space, file will be written somewhere like , below code may help you in this regard
FileOutputStream fOut = null;
OutputStreamWriter osw = null;
try{
fOut = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
osw = new OutputStreamWriter(fOut);
osw.write("yourString data");
osw.close();
fOut.close();
}catch(Exception e){
e.printStackTrace(System.err); }
you can try this. I m using this for storing download images
String cacheDir=
context.getCacheDir();
File file= new File(cacheDir,
"test.dat");
FileOutputStream out = new
FileOutputStream(file);
Save file in internal memory but you can not see the files which saved in internal memory.
Use this code to save the file in internal memory.
public boolean saveImageToInternalStorage(Bitmap image,Context context)
{
try {
FileOutputStream fos = context.openFileOutput("photo.jpg", Context.MODE_WORLD_READABLE);
image.compress(Bitmap.CompressFormat.JPEG, 100, fos);
// 100 means no compression, the lower you go, the stronger the compression
fos.close();
return true;
}
catch (Exception e) {
Log.e("saveToInternalStorage()", e.getMessage());
}
return false;
}
Read this article to Save file in internal and external memory.

Categories

Resources