Android:Writing data to a file - android

with the below piece of code, I'm able to create a new file called output.txt and i'm able to write data. Problem is this file gets recreated once i close my app and then open my app again. As because i create this in onCreate().
But i would like to have the file created only once and then i would like to append the data there after.
private File outputFile = null;
FileOutputStream fOut = null;
OutputStreamWriter osw = null;
#Override
public void onCreate(Bundle savedInstanceState) {
....
if(outputFile == null)
outputFile = new File("/storage/new/output.txt");
if(osr==null){
try {
osr = new FileOutputStream(outputFile);
out = new DataOutputStream(osr);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
.....
try {
out.writeBytes(data);
out.flush();
//out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Try setting the append flag to true when constructing your FileOutputStream
osr = new FileOutputStream(outputFile, true);

Try,
FileOutputStream fileOut = openFileOutput(outputFile, MODE_APPEND);
OutputStreamWriter osw = new OutputStreamWriter(fileOut);
osw.writeBytes(data);
osw.flush();

Related

How to write a JSON file on internal storage

I would like to write json file on internal storage but I can not handle it. Here is my code:
String answers_json = data.getExtras().getString("answers");
Log.d("****", "****************** WE HAVE ANSWERS ******************");
Log.v("ANSWERS JSON", answers_json);
Log.d("****", "*****************************************************");
try {
File file = new File (getFilesDir(),"answers.json");
FileWriter fileWriter = new FileWriter(file);
BufferedWriter writer = new BufferedWriter(fileWriter);
writer.write("answers");
writer.flush();
writer.close()
I have tried so many variants, but it ends always with an error "open failed" or whenever everything is fine, no file finds on my phone (that means nothing happened). What is wrong on my side?
I got it. This is working for me...
try {
String FILENAME = "answers.json";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_APPEND);
assert answers_json != null;
fos.write(answers_json.getBytes());
fos.close();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
greets and thank for your help.
This may help you:
private void downloadAndStoreJson(String url,String tag){
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url);
String jsonString = json.toString();
byte[] jsonArray = jsonString.getBytes();
File fileToSaveJson = new File("/sdcard/appData/LocalJson/",tag);
BufferedOutputStream bos;
try {
bos = new BufferedOutputStream(new FileOutputStream(fileToSaveJson));
bos.write(jsonArray);
bos.flush();
bos.close();
} catch (FileNotFoundException e4) {
// TODO Auto-generated catch block
e4.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
jsonArray=null;
jParser=null;
System.gc();
}}

Writing byte[] array to text file in Android

So many examples for this question. I tried and still doesn't work.
Test.txt file is created. But no data is written into the test.txt file.
What is wrong with my code? I have permission in the Manifest file as
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Code:
String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() +
"/PrintFiles";
File file = new File(file_path+"/test.txt");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
FileOutputStream fos = null;
try {
fos = openFileOutput(file.getName(), Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] b = {65,66,67,68,69};
fos.write(b);
fos.flush();
fos.close();
Cause, you are creating file in SDCard but writing in Internal Storage. Try as follows...
String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() +
"/PrintFiles";
File file = new File(file_path+"/test.txt");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] b = {65,66,67,68,69};
fos.write(b);
fos.flush();
fos.close();
From the doc openFileOutput will
Open a private file associated with this Context's application package for writing. Creates the file if it doesn't already exist.
those files are under the.
data > data > your app id > files
but your file is not in internal folder its in external storage..
Change this line
fos = openFileOutput(file.getName(), Context.MODE_PRIVATE);
into
fos=new FileOutputStream(file);
And try..

Overwriting data using files

i created a file and when i run the program, the data is been written in to the file but when i run the program again the new data over write on old data.
i need once the program is running and gathers data, these data are writable into the file in cascade next each other without overwriting on previous data in file.
this code running successful but when i run the program again the over writing happens which i don need that, i need to save previous data in side the file and write the new data next it and soon.
after edit this code its looks like:
public class MainActivity extends Activity {
File file;
File sdCard;
FileOutputStream fos;
OutputStreamWriter myOutWriter;
String FileName = "Output3.txt";
String eol;
OutputStream fos1;
FileWriter fw ;
BufferedWriter writer;
BufferedWriter bw ;
PrintWriter out;
EditText txtData;
Button btnWriteSDFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sdCard =getExternalFilesDir(null);
file = new File(sdCard,FileName);
txtData = (EditText) findViewById(R.id.editText1);
btnWriteSDFile = (Button) findViewById(R.id.button1);
btnWriteSDFile.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
try {
fos = new FileOutputStream(file);
myOutWriter =new OutputStreamWriter(fos);
eol = System.getProperty("line.separator");
writer = new BufferedWriter(myOutWriter);
writer.append(txtData.getText() + eol);// write this text.
writer.flush();
fos.close();
Toast.makeText(v.getContext(),"Done writing SD 'Output.txt'", Toast.LENGTH_SHORT).show();
txtData.setText("");
} catch (Exception e) {
// e.printStackTrace();
Toast.makeText(v.getContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
}
finally{
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
}
please,can any one answer me?
Instead of using OutputStreamWriter use Filewriter FileWriter fileWritter = new FileWriter(file,true); when u pass true it appends the contents.try this
FileWriter myOutWriter = new FileWriter(file.getName(),true);
eol = System.getProperty("line.separator");
writer = new BufferedWriter(myOutWriter);
writer.write(txtData.getText() + eol);// write this text.
writer.close();
fos.close();
Change this line:
fos = new FileOutputStream(file);
To:
fos = new FileOutputStream(file, true);
This opens the file so that data can be appended.
JavaDocs for FileOutputStream
use
FileWriter writer = new FileWriter("yourfilename", true);
second parameter should be passed as true which will append data instead of overwriting
try {
File myFile = new File(Environment.getExternalStorageDirectory() + File.separator + "test.txt");
// this changed bye fos = new FileOutputStream(myFile) to
fos = new FileOutputStream(myFile,true);
//FileWriter writer = new FileWriter("yourfilename", true);
myOutWriter = new OutputStreamWriter(fos);
eol = System.getProperty("line.separator");
writer = new BufferedWriter(myOutWriter);
writer.append("\n");
writer.append(txtData.getText() + eol);// write this text.
writer.flush();
fos.close();
Toast.makeText(v.getContext(),
"Done writing SD 'Output.txt'", Toast.LENGTH_SHORT)
.show();
txtData.setText("");
} catch (Exception e) {
// e.printStackTrace();
Toast.makeText(v.getContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
} finally {
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Enjoye i have tested it is work for me.

Android:Cannot open file Not enough disk space

I have an application consist on reading AND saving an xml file and to write it if internet connection is available,else it will read the file already saved on the terminal.
WriteFeed function:
// Method to write the feed to the File
private void WriteFeed(RSSFeed data) {
FileOutputStream fOut = null;
ObjectOutputStream osw = null;
try {
fOut = openFileOutput(fileName, MODE_PRIVATE);
osw = new ObjectOutputStream(fOut);
osw.writeObject(data);
osw.flush();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
WriteFeed function:
// Method to read the feed from the File
private RSSFeed ReadFeed(String fName) {
FileInputStream fIn = null;
ObjectInputStream isr = null;
RSSFeed _feed = null;
File feedFile = getBaseContext().getFileStreamPath(fileName);
if (!feedFile.exists())
return null;
try {
fIn = openFileInput(fName);
isr = new ObjectInputStream(fIn);
_feed = (RSSFeed) isr.readObject();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
fIn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return _feed;
}
I have enough diskSpace ,sometimes i get "MemoryCach will use up to 16 Mb" ,always i get "Not enough disk space,will not index" and "FeatureCode > cannot open file"
whats wrong in my app?

Android External Storage BufferedWriter doesn't accept NewLine

i have problem with file writing. I want to create OnClick method of button that add line to file on sdcard but instead it delete previous line and put all content in place of current one. In result i got only the Text i put at the last click of Button, here is my code:
if (txtFile.createNewFile() || txtFile.isFile()) {
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(txtFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
BufferedWriter bwriter = new BufferedWriter(myOutWriter);
EditText desc__ = (EditText)findViewById(R.id.descriptionEditTExt);
try {
bwriter.newLine();
bwriter.write(lat+"|"+lng+"|"+desc__.getText().toString()+"|"+f+"|"+position);
bwriter.close();
myOutWriter.close();
fOut.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
/* handle directory here */
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Please rewrite your FileOutputStream constructor as
FileOutputStream fos = new FileOutputStream(file, true);
here is suggests that your file will be opened in the append mode which will solve your first problem..
secondly if you want to add new line to the file use "\r\n" string
e.g. fos.write("\r\n".getBytes());
Hope this helps..

Categories

Resources