0
PrintWriter writer = new PrintWriter("testfile.txt", "UTF-8");

Following this link:

How do I create a file and write to it in Java?

it does not specify a path link in the first argument of PrinterWriter(), but only a file name. I followed it exactly, but it then shows a FileNotFoundException. I ran the app once, but the exception still shows up. I assumed after running the app, a file would be automatically created, but it doesn't seem to do that. I am using eclipse for android, so I'm not sure where the file should have been created. If there is any confusion don't hesitate to ask questions, thanks.

Community
  • 1
  • 1
  • Well presumably the `testfile` argument is specifying a file in a directory that doesn't exist... – Jon Skeet Aug 02 '14 at 22:46
  • Well it sounds like you need to look for an Android-specific tutorial, that explains what the current directory is going to be, where you can write files etc. – Jon Skeet Aug 02 '14 at 22:50
  • @JonSkeet I tried, but either my googling skills are horrible, or there doesn't seem to be any good, informational website on android files. Is it possible that you can point me to one? –  Aug 02 '14 at 22:53

2 Answers2

0

Probably, you just have no permission to create files in the root directory. Try this:

PrintWriter writer = new PrintWriter(new File(context.getFilesDir(), "testfile.txt"), "UTF-8");

or if you want to save file on sdcard

PrintWriter writer = new PrintWriter(new File(Environment.getExternalStorageDirectory(), "testfile.txt"), "UTF-8");

Don't forget to add permission WRITE_EXTERNAL_STORAGE in this case

jauser
  • 294
  • 1
  • 4
-2

I don't develop on android but according to this and this code here, I think you might have to wrap an OutputStream with a PrintWriter for it to work.

  • Nonsense. See the last constructor listed in your first citation. – user207421 Aug 03 '14 at 00:04
  • @EJP I was going by the "Class Overview" of the first link. Looking again, I see there is a constructor for how the OP used it but the class overview did specify its use as a wrapper. It also says it does not throw an IOException when it clearly did for OP so I'm not sure if any of that is correct. – user3902960 Aug 03 '14 at 00:25
  • PrintWriter(String, String) throws FileNotFoundException. Have another look. This answer should be deleted. – user207421 Aug 04 '14 at 22:23