0

I am an android newbie and wrote this code for file handling but for some reason i am always getting back null values from the file. I also tried using readline() but got the same result. Would appreciate any help.

 @Override public void onClick(View v) { // TODO Auto-generated method stub String file = "test123"; try { OutputStream out = v.getContext().openFileOutput(file, MODE_PRIVATE); InputStream in = v.getContext().openFileInput(file); WriteFile(out); String str = ReadFile(in); Toast.makeText(v.getContext(), str, Toast.LENGTH_LONG); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); } public static void WriteFile(OutputStream out) { OutputStreamWriter tmp = new OutputStreamWriter(out); try { for (int i = 0 ; i < 10; i++) { tmp.write(i); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static String ReadFile(InputStream in) { InputStreamReader tmp = null; String str = ""; tmp = new InputStreamReader(in); BufferedReader reader=new BufferedReader(tmp); try { for (int i = 0; i < 10; i++) { str += " " + reader.readLine(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return str; } 

}

2
  • I guess the error is that you use the same file to read from and to write to. Try to use different files. Commented Jan 27, 2012 at 10:38
  • i want to read from the file i have already written into. Commented Jan 27, 2012 at 20:54

1 Answer 1

1

String file = "test123"; So, the path of your file should be {root}/test123 Try defining a path were you can access to see if it has written something. (usually : /mnt/storage/your_file) Then, you'll be able to determine if the Write/Read process works or not

Note : Take a look at FileOutputStream, it already implements lots of useful methods

Sign up to request clarification or add additional context in comments.

1 Comment

so is it not recommended to use openFileOutput()? I am a bit confused because openFileOutput(filename) doesn't like path separators in the input.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.