i'm using the below code to save log data to a file.
However, every time a new call is made, the old content is gone.....
i can't figure out what the issue is however....
public void writeToFile(String fileName, String textToWrite) {
FileOutputStream fOut = null;
try {
File root = new File(Environment.getExternalStorageDirectory() , fileName);
if (! root.exists()){
root.createNewFile();
}
fOut = new FileOutputStream(root);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(textToWrite);
myOutWriter.flush();
myOutWriter.close();
}
catch (Exception e) {
new MailService().mailMessage(e.toString());
}
finally{
if(fOut != null){
try{
fOut.close();
}
catch(Exception ex){
}
}
}
}
You need to pass second parameter boolean true to FileOutputStream constructor which indicates the file will be opened in append mode rather than write mode.
FileOutputStream out=new FileOutputStream("myfile");
Everytime you execute the above code it will open the file in write mode so that the new content will overwrite the old content. However, the FileOutputStream constructor accepts a second argument which is a boolean indicating whether to open the file in append mode.
FileOutputStream out=new FileOutputStream("myfile",true);
The above code will open the file in append mode so that the new content will be appended to the end of old content.
To know more about FileOutputStream constructors see this.
Related
Here's my code:
String content = mEditText.getText().toString();
FileOutputStream fos;
try {
fos = openFileOutput(title, MODE_PRIVATE);
fos.write(content.getBytes());
Toast.makeText(EditActivity.this, "Saved to "+getFilesDir() + "/" + title, Toast.LENGTH_LONG).show();
fos.close();
saved = true;
} catch (IOException e) {
Toast.makeText(EditActivity.this, "Error happened", Toast.LENGTH_SHORT).show();
}
If I run the code like this, it tells saved to /data/data/mypackagename/files/FileTitle. I want it to save the file in another directory for example save to /data/data/mypackagename/files/userData/FileTitle.I don't know any way to do this
What you need is the File constuctor that takes a parent File and a relative path to file. You've correctly established that openFileOutput() creates the file in getFilesDir(), so the code would look something like this:
FileOutputStream fos = null;
try {
final File dir = new File(getFilesDir(), "some/long/path");
dir.mkdirs();
final File file = new File(dir, "file.txt");
fos = new FileOutputStream(file);
// Use fos...
} catch (IOException e) {
// Handle error...
} finally {
if (fos != null) {
try {
fos.close()
} catch (IOException ignore) {
// Close quietly.
}
}
}
File is just a pointer, it may point to a directory, it may even point to something that's not there yet, like a new file. FileOutputStream will create a file if it doesn't exist.
If you choose to place your new file in another directory, make sure it exists first by calling mkdirs() on the directory.
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.
I am trying to add data to a text file in android using the code below but it only overwrites the data with one line of data.
private void copyImageToMemory(File outFile , Float number) {
try {
BufferedOutputStream fos = new BufferedOutputStream(
new FileOutputStream(outFile));
PrintWriter pw = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(fos)));
pw.append("result"+number);
pw.close();
maxSpeed=0;
} catch (FileNotFoundException e) {
Log.e(TAGFile, "FileNotFoundException");
}
}
The FileOutputStream constructor allows to specify whether it should append to an already existing file or not:
new FileOutputStream(file, true);
will create a stream that appends to the given file.
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 making a bookmark for web browser app this code is saving and loading the data but it is not appending data in new line...every time i am pressing the button it is overwriting previous data ..I want that every time i call bookmarkload(); method in main activity it should save data in new line instead of overwriting it..Please help me as i am new to android tell what line to enter where..so that it start appending data..Thanks in advance ..please give answer in detail if possible.
public class Bookmark {
FileOutputStream fos;
FileInputStream fis = null;
public void bookmarksave(Context context,String FILENAME,String data){
try {
fos = context.openFileOutput(FILENAME, 0);
fos.write(data.getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public String bookmarkload(Context context,String FILENAME){
String collected =null;
try{
fis =context.openFileInput(FILENAME);
byte[] dataArray = new byte[fis.available()];
while(fis.read(dataArray) != -1){
collected = new String(dataArray);
fis.close();
}
} catch(FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return collected;
}
}
fos.write(System.getProperty("line.separator").getBytes());
Try this one... new data will be appended in new line..
change the Line fos = context.openFileOutput(FILENAME, 0); to
fos = context.openFileOutput(FILENAME, Context.MODE_APPEND);
This will open your file in append mode, instead of the default (override) mode.
You should also add a new line, otherwise you continue in the same line as before:
fos.write(System.getProperty("line.separator").getBytes());
You can use SharedPreferences to save your bookmark.It's very convenience.And if you want to use File to store them.You can use new FileOutputStream(filename,true) ,true means bytes will be written to the end of the file rather than the beginning.