Can anyone help me with this my goal is to read the contents of MyNotes.txt.
Can anyone help me with this my goal is to read the contents of MyNotes.txt. As you can see from my code i already got the directory and the name of the file to read (which can also be seen in the Dialog Title) but I’m confused about how to read the actual contents of the file to my EditText.
]]>
< ![CDATA[
Using Java, a method to read a file and store its content in a string could be:
public static String readFileContent(File f) {
FileInputStream fis=null;
try {
fis=new FileInputStream(f);
int file_length=(int)f.length();
byte[] data=new byte[file_length];
fis.read(data, 0, file_length);
return new String(data, “utf-8”);
} catch(Exception e) {
return null;
} finally {
if(fis!=null) try { fis.close(); } catch(Exception e) {}
}
}
It’s Java so it cannot be mapped exactly to JavaScript, but the interesting part is between the “try” and “catch”: it shows how to open the file, read bytes and put this is a string.
Not really an answer, but I hope this can help anyway…
]]>
< ![CDATA[
Thanks 🙂
]]>
< ![CDATA[
You could also use BufferedReader.readLine() repeatedly to read in all lines.
Or if you want to store an object, use ObjectInput/Output… it depends on how the notes are stored
]]>
< ![CDATA[
That’s what i was originally playing with but I could only get it to read the 1st Line of the file, but yeah now that you mention it I never thought about using a loop lol.
Notes are just in a txt file and each ones separated with a # character like this.
This is a test
#
This is another test
#
I plan to replace the # character in the dialog though so the Notes can be read with a break inbetween so it looks cleaner.
]]>
< ![CDATA[
Finally!
I did it well sort of, its showing a seperate Toast for each line of the file, I want it to show the contents in 1 Toast though.
var fileContents;
while ((fileContents = readFile.readLine()) != null){
Android.makeNewToast(fileContents, false).show();
}
readFile.close();
]]>
< ![CDATA[
You’re almost done: merge the lines in a single string this way:
var content = “”;
while(…) {
content += line;
}
# are not displayed because on each loop iteration readLine is called twice. Maybe simply drop this superfluous line then.
A great and easy way to store structured content is to use JSON. Easier than XML and you don’t have to mess with custom separators or encoding.
]]>
< ![CDATA[
I use:
var finalString=””;
var l;
while ((l=reader.readLine())!=null)finalString+=(l+”\n”);
]]>
< ![CDATA[
Yeah I messed up and left a line of code in there. I took it out and now it reads the file line by line 🙂 still on separate Toasts but what you just wrote should fix that cheers. I’ll checkout JSON soon i heard of it but never tried it. Didn’t even no what it was for tbh.
]]>
< ![CDATA[
Took 7hrs!! but I got there in the end 😀
Cheers for the help.
]]>