获取输入流的大小问题

haha1699 2009-02-17 03:54:56

Enumeration e=FileSystemRegistry.listRoots(); //获取文件路径
String root = (String) e.nextElement();
String url="file:///"+root+filename;
FileConnection conn=null;
try{
conn=(FileConnection)Connector.open(url,Connector.READ); //打开文本文件
DataInputStream in=conn.openDataInputStream(); //打开数据输入流
int size=in.available(); //检查文本文件大小
System.out.println(size);
byte[] buffer=new byte[size]; //创建文本缓冲区
in.read(buffer); //将所有内容读入缓冲区
String content=new String(buffer,encoding); //用缓冲区中的内容创建字符串
content=content.substring(1);
buffer=null; //释放缓冲区
in.close(); //关闭数据输入流
conn.close(); //关闭文本文件
in=null;
.....

int size=in.available();获取的大小为0,但如果手动设置buffer大小,是能够读取文件的数据,那么说输入流应该是正常的,但为什么in.available()却不能获得输入流的大小呢,
...全文
1033 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
kf156 2009-02-17
  • 打赏
  • 举报
回复
This method should be overridden by subclasses.
主要看这方法有没被重写过
没重写肯定是返回0的
haha1699 2009-02-17
  • 打赏
  • 举报
回复
为什么6楼的那个in.avliable返回的却不是0呢
在API里也有说The available method for class InputStream always returns 0,但事实上却能返回其他值
网络咖啡 2009-02-17
  • 打赏
  • 举报
回复
因为MIDP API中规定avliable方法的返回值是0的

public int available()
throws IOExceptionReturns the number of bytes that can be read (or skipped over) from this input stream without blocking by the next caller of a method for this input stream. The next caller might be the same thread or another thread.
The available method for class InputStream always returns 0.

This method should be overridden by subclasses.


Returns:
the number of bytes that can be read from this input stream without blocking.
Throws:
IOException - if an I/O error occurs.
haha1699 2009-02-17
  • 打赏
  • 举报
回复
String strReturn = "";
InputStream in = null;
try{
in = getClass().getResourceAsStream(url);
int size=in.available();
byte[] buffer= new byte[size];
in.read(buffer);
in.close();
strReturn=new String(buffer,"UTF-8");
buffer=null;
}catch(Exception e){
}finally{
in = null;
}

这是我另外一个程序的代码,这里的in.available()能正常工作
不同的是,这里的文件是在jar里的,上面的那个文件是在手机文件系统里的,会不会是这个原因呢
kf156 2009-02-17
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 xuxing0614 的回复:]
available(); 这个方法好像是没有实现的返回永远是 0。。一般不要使用这个方法。
[/Quote]

是的,InputSteam的available()方法如果没被重写的话永远返回0。
隧便 2009-02-17
  • 打赏
  • 举报
回复
available(); 这个方法好像是没有实现的返回永远是 0。。一般不要使用这个方法。
haha1699 2009-02-17
  • 打赏
  • 举报
回复
用的仿真器是sun wtk的defultcolorphone,他自己的仿真器不会连自己的API都不能实现吧
yanhan0615 2009-02-17
  • 打赏
  • 举报
回复
这个available()用的时候确实跟机型相关,有歧义,用FileConnection里的size()方法来获取就肯定是正确的了
kf156 2009-02-17
  • 打赏
  • 举报
回复
之前我也有遇到这问题,好像不是一定的。理论上是可以的,要看API是否实现了。
如果你只是想得到文件大小。
可以直接用int size=(int)conn.fileSize();

13,100

社区成员

发帖
与我相关
我的任务
社区描述
Java J2ME
社区管理员
  • J2ME社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧