Search code examples
filejava-mejsr75

J2ME read file byte by byte


I have encountered many site examples and almost all are like this:
http://www.java2s.com/Code/Java/J2ME/ReadDisplayFile.htm
http://www.roseindia.net/j2me/read-file.shtml
They only show how to read a file from a resource file, not on the file system.
This is my current code:

InputStream is;
String path = "file:///root1/photos/a.txt"
try {
     fc = (FileConnection)Connector.open(path,Connector.READ);
     is = fc.openInputStream();
     int a = is.available();
     char buf = 0;
     String buff = new String();
     while (buf!=-1){
           buf=(char)is.read();
           buff+=buf;                      
     }          
 } catch (IOException ex) {} 

but it doesn't work, and the infinite loop is created.

is.available(); (int a) returns 0 (Why?) and file:///root1/photos/a.txt exists and contains: Hi!Hello!

How can I get this to work?

EDIT: I figured it out, (buf!=-1) is checking -1 on a unsigned char so it is never negative. Stewpid mistake. I just changed it to int and it worked. Sorry for bothering. I hope someone will find this useful if it doesn't get deleted


Solution

  • better you try this

    InputStream is;
    String path = "file:///root1/photos/a.txt"
    try {
         fc = (FileConnection)Connector.open(path,Connector.READ);
         is = fc.openInputStream();
         int a = is.available();
         char buf = 0;
         StringBuffer buff = new StringBuffer();
         int i=0;     
         String temp1=null;byte bt[]=null;   
         while ((i=is.read())!=-1){
               bt=new byte[1];
               bt[0]=(byte)i;
               temp1=new String(bt);
               buf.append(temp1);
               temp1=null;
               bt=null;
    
         }          
     } catch (IOException ex) {} 
    

    buf is string buffer which have the string.