Original code and its working saving the data to the SD Card
// Writing data to internal storage
btnSaveData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isSDCardWritable()) {
String dataToSave = etData.getText().toString();
try {
// SD Card Storage
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File(sdCard.getAbsolutePath()+"/MyFiles");
directory.mkdirs();
File file = new File(directory, "text.txt");
FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(fos);
// write the string to the file
osw.write(dataToSave);
osw.flush();
osw.close();
. . .
And then I changed the code to append a new values as it should be according to what I need:
osw.append(dataToSave);
osw.flush();
osw.close();
Problem is: It overwrites the text file instead of appending. What did I miss? Thanks for helping
Constructor FileOutputStream( File file ) always overwrites file. If you want to append to file you have to use more generic constructor FileOutputStream( File file, boolean append ). If you set parameter 'append' to true file is not overwritten.
Related
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));
I am using the following code to store in a file some data.
(mydata is the data the user enters (double list) and dates_Strings is a string list where i store dates)
public void savefunc(){
SimpleDateFormat thedate = new SimpleDateFormat("dd/MM/yyyy",Locale.US);
Date d=new Date();
String formattedDate=thedate.format(d);
Log.d("tag","format"+formattedDate);
dates_Strings.add(formattedDate);
double thedata=Double.parseDouble(value.getText().toString().trim());
mydata.add(thedata);
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File (sdCard, "MyFiles");
directory.mkdirs();
File file = new File(directory, filename);
FileOutputStream fos;
try {
fos = new FileOutputStream(file);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
for (int i=0;i<mydata.size();i++){
bw.write(mydata.get(i)+","+dates_Strings.get(i)+"\n");
}
value.setText("");
bw.flush();
bw.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
The problem is that if I enter some data in 06/05/13 and later some data in 07/05/13 , the file contains only the last data from the last date.I want to keep all the data.
Open the fileoutputstream in append mode
fos = new FileOutputStream(file, true);
Use fos = new FileOutputStream(file, true); to append data to the file instead of overwriting it.
FileOutputStream documentation
I have tried so many ways to write file in external as card but not working. Please suggest me what to do.
The code snippet that I wrote is as follows:
final String directoryFile = "file:///"+"mnt/extsd/Test";
String filename = "TextData.txt";
Context context;
//String file=Environment.getExternalStorageDirectory()+ "/TextData.txt";
//String file = "mnt/extsd/TextData.txt";
//String file=Environment.getExternalStorageDirectory()+ "/RudimentContent/test.txt";
//File root = android.os.Environment.getExternalStorageDirectory();
//File dir = new File (root.getAbsolutePath() + "/download");
//File path = Environment.getExternalStorageDirectory();
//String filename = "TextData.txt";
//String fileName = "TextData.txt";
//String path = "Environment.getExternalStorageDirectory()/TextData.txt";
//File path = Environment.getExternalStorageDirectory();
public void onClick(View v)
{
// write on SD card file data in the text box
// dir.mkdirs();
//File file = new File(dir, "myData.txt");
//String fileName = surveyName + ".csv";
//String headings = "Hello, world!";
//File file = new File(path, fileName);
//path.mkdirs();
//OutputStream os = new FileOutputStream(file);
//os.write(headings.getBytes());
//create path
//create file
//File outFile = new File(Environment.getExternalStorageDirectory(), filename);
//File directoryFile = new File("mnt/extsd", "Test");
//directoryFile.mkdirs();
//create file
//File file = new File(Environment.getExternalStorageDirectory(), filename);
try{
File myFile = new File(directoryFile, filename); //device.txt
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(txtData.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),"Done writing SD "+myFile.getPath(),Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
});
I have commented on so may tried codes also. When I write in internal sd card then its working but not with external. Please suggest.
I had this before.
The reason you're having this exception is due to some bizarre ways the framework handles files and folders.
on my case was that I was testing, and all was working, and I deleted the testing folder and since then the system keeps trying to write on the deleted folder. I removed the project from the phone and reboot it and started working again.
furthermore, I suggest you a quick reading on this answer What is the best way to create temporary files on Android? and the comments of this answer... as there is a lot of useful information if you want to create a good app.
just set permission like this
android.permission.WRITE_EXTERNAL_STORAGE
If you're using API Level 8 or greater, use getExternalFilesDir() to open a File that represents the external storage directory where you should save your files. This method takes a type parameter that specifies the type of subdirectory you want, such as DIRECTORY_MUSIC and DIRECTORY_RINGTONES (pass null to receive the root of your application's file directory).
This method will create the appropriate directory if necessary.
If you're using API Level 7 or lower, use getExternalStorageDirectory(), to open a File representing the root of the external storage. You should then write your data in the following directory:
/Android/data//files/
You will have to set the permissions too:
android.permission.WRITE_EXTERNAL_STORAGE
try this
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
and add this in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
EDIT: By using this line you can able to see stores images in the gallery view.
sendBroadcast(new Intent(
Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
i tried the code below!!every time it replaces contents from file "textfile.txt" i want the user to add files to SD card with name which they have entered as "filename"
i have registered onclick listener on save button
Code:
EditText filename =(EditText) findViewById(R.id.filename);
EditText filecontent =(EditText) findViewById(R.id.filecontent);
public void onClick(View view)
{
String str = filename.getText().toString();
String str2= filecontent.getText().toString();
file sdCard = Environment.getExternalStorageDirectory();
File directory = new File (sdCard.getAbsolutePath() +"/MyFiles");
directory.mkdirs();
File file = new File(directory,"textfile.txt");
file.createNewFile();
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(str);
osw.write(" ");
osw.write(str2);
osw.flush();
osw.close();
}
If i understood your question correctly, here is your solution:
change "textfile.txt" inside File file = new File(directory,"textfile.txt");
to filename.
Final result shouldlook : File file = new File(directory,filename);
Well then you have to give each file a unique name.
change it to
File file = new File(directory,str+".txt");
it will store file S THE NAME GIVEN BY USER!!!
I have a little issue with creating folders for my application in Internal Memory. I'm using this piece of code :
public static void createFoldersInInternalStorage(Context context){
try {
File usersFolder = context.getDir("users", Context.MODE_PRIVATE);
File fileWithinMyDir = new File(usersFolder, "users.txt"); //Getting a file within the dir.
FileOutputStream out = new FileOutputStream(fileWithinMyDir); //Use the stream as usual to write into the file.
File dataFolder = context.getDir("data", Context.MODE_PRIVATE);
File fileWithinMyDir2 = new File(dataFolder, "data.txt"); //Getting a file within the dir.
FileOutputStream out2 = new FileOutputStream(fileWithinMyDir2); //Use the stream as usual to write into the file.
File publicFolder = context.getDir("public", Context.MODE_PRIVATE);
File fileWithinMyDir3 = new File(publicFolder, "public.txt"); //Getting a file within the dir.
FileOutputStream out3 = new FileOutputStream(fileWithinMyDir3); //Use the stream as usual to write into the file.
} catch(FileNotFoundException e){
e.printStackTrace();
}
}
So folders are created but in front of their name there is the beginning "app_" : app_users, app_data, app_public. Is there a way to create the folders with the name given by me? And another question : I want to first create folder Documents and than all other folders "Data, Public, Users" on it.... And the last question : How can I give the right folder path if I wanted to create a file in Documents/Users/myfile.txt in Internal Memory?
Thanks in advance!
You can use this :
File myDir = context.getFilesDir();
String filename = "documents/users/userId/imagename.png";
File file = new File(myDir, filename);
file.createNewFile();
file.mkdirs();
FileOutputStream fos = new FileOutputStream(file);
fos.write(mediaCardBuffer);
fos.flush();
fos.close();
Is there a way to create the folders with the name given by me?
Use getFilesDir() and Java file I/O instead of getDir().
How can I give the right folder path if I wanted to create a file in Documents/Users/myfile.txt in Internal Memory?
Use getFilesDir() and Java file I/O, such as the File constructor that takes a File and a String to assemble a path.