【问题标题】:J2ME read file byte by byteJ2ME 逐字节读取文件
【发布时间】:2012-04-30 19:47:02
【问题描述】:

我遇到过很多网站示例,几乎都是这样的:
http://www.java2s.com/Code/Java/J2ME/ReadDisplayFile.htm
http://www.roseindia.net/j2me/read-file.shtml
它们仅显示如何从资源文件中读取文件,而不是在文件系统上。
这是我当前的代码:

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) {} 

但它不起作用,并且创建了无限循环。

is.available(); (int a) 返回 0(为什么?)并且 file:///root1/photos/a.txt 存在并包含:Hi!Hello!

我怎样才能让它工作?

编辑:我想通了,(buf!=-1)unsigned char 上检查 -1,所以它永远不会是负数。愚蠢的错误。我只是将其更改为 int 并且它有效。抱歉打扰了。如果不被删除,我希望有人会发现这很有用

【问题讨论】:

  • 对于有人会发现这很有用将您的编辑复制到答案中并接受它,this is a recommended way。如果声望低于 100,您可能需要等待几个小时(我认为是 8 小时)才能发布自我回答
  • 是的,我想这样做,但正如你所说,我的代表

标签: file java-me jsr75


【解决方案1】:

你最好试试这个

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 是包含字符串的字符串缓冲区。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-15
    • 2013-12-06
    • 1970-01-01
    • 2015-10-23
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    相关资源
    最近更新 更多