I found the problem. An InputStreamReader will not read() to a
String.toCharArray(). You have to use a char[]. Here is my new
function for reference:
public String loadFile(String filename)
{
try
{
FileInputStream fis = openFileInput(filename);
InputStreamReader in = new InputStreamReader(fis,
"utf-8");
File file = new
File("/data/data/com.android.webbed/files/" +
filename);
char[] buff = new char[(int) file.length()];
in.read(buff);
String contents = new String(buff);
return contents;
}
catch(FileNotFoundException e)
{
e.printStackTrace();
return "File Not Found";
} catch (IOException e) {
e.printStackTrace();
return "IO Exception";
}
}
On Feb 11, 10:01 pm, David <[email protected]> wrote:
> Unfortunately, that didn't solve my problem. Any other help?
>
> P.S. I tried that tutorial in normal java and it worked, but not in
> android.
>
> On Feb 11, 5:51 pm, Mark Murphy <[email protected]> wrote:
>
> > David wrote:
> > > Hey guys, I need some help with reading the contents of a file. I have
> > > a plaintext file called 'test' in my app's files/ directory. I have
> > > this code to read it:
>
> > > public String loadFile(String filename)
> > > {
> > > try
> > > {
> > > FileInputStream fis = openFileInput(filename);
> > > InputStreamReader in = new InputStreamReader
> > > (fis);
> > > String contents = "";
> > > in.read(contents.toCharArray());
> > > return contents;
> > > }
> > > catch(FileNotFoundException e)
> > > {
> > > e.printStackTrace();
> > > return null;
> > > } catch (IOException e) {
> > > e.printStackTrace();
> > > return null;
> > > }
> > > }
>
> > > I pass the filename to the function like this:
> > > String contents = "";
> > > contents = loadFile('test');
>
> > > But every time it returns nothing. I have tested it and it doesn't go
> > > into one of the catch es, but it apparently reads nothing from the
> > > file. What am I doing wrong?
>
> > Phooey. Let's try that again...
>
> > Try this example:
>
> >http://www.exampledepot.com/egs/java.io/ReadLinesFromFile.html
>
> > Except that the first line will need to use an InputStreamReader on the
> > InputStream you get from openFileInput().
>
> > --
> > Mark Murphy (a Commons Guy)http://commonsware.com
> > _The Busy Coder's Guide to Android Development_ Version 2.0 Published!
--~--~---------~--~----~------------~-------~--~----~
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
-~----------~----~----~----~------~----~------~--~---