Your exception handling is not well structured, and you don't close
your output stream.
I'd write it like this:
try {
FileOutputstream foStream =
getBaseContext().openFileOutput("myfile.txt", 0);
PrintStream pStream = new PrintStream(foStream);
try {
pStream.print("This content has been printed.");
} finally {
pStream.close();
}
} catch (IOException ex) {
throw new RuntimeException("Could not write myfile.txt: " + ex, ex);
}
At a minimum. You may want to handle the file specially if the output
gets an error -- deleting the file, or closing it and then renaming it
only if the writing was successful.
Be aware that PrintStream will suppress throwing of IOExceptions, so
using PrintStream, if you care about the output, you should do
pStream.checkError() and take appropriate action if it returns true.
You may also want to do some more sophisticated error handling than
just rethrowing -- but this will at least cause the stacktrace to be
reported properly in the log, and the user will be shown a force quit
dialog.
On Apr 23, 2:24 pm, venkata raidu <[email protected]> wrote:
> Hi Mark,
> Thanks for the reply. I have gone through the web page which you
> forwarded.
> It seems like, the article is related to file output on to a
> desktop.
> But, I need something specific to Android, where I can print my
> data onto a temporary file on android.
>
> I was trying the following code:
>
> public class Packager extends Activity {
> /** Called when the activity is first created. */
> @Override
> public void onCreate(Bundle savedInstanceState) {
> super.onCreate(savedInstanceState);
> setContentView(R.layout.main);
> FileOutputStream foStream;
> PrintStream pStream;
>
> try {
> foStream =
> getBaseContext().openFileOutput("myfile.txt", 0);
> pStream = new PrintStream(foStream);
> pStream.print("This content has been printed");
>
> } catch (FileNotFoundException e) {
> // TODO Auto-generated catch block
>
> }
> }
>
> }
>
> Please let me know if anything is wrong in the above code.
>
> Thanks,
> Venkata
>
> --
> You received this message because you are subscribed to the Google
> Groups "Android Developers" group.
> To post to this group, send email to [email protected]
> To unsubscribe from this group, send email to
> [email protected]
> For more options, visit this group
> athttp://groups.google.com/group/android-developers?hl=en
--
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en