一个读取文件的方法:
Android:
public String readFile(String fileName) throws Exception{
ByteArrayOutputStream outStream=new ByteArrayOutputStream();
FileInputStream fis=context.openFileInput(fileName);
byte [] buffer=new byte[1024];
int length=fis.read(buffer);//1
while(length != -1){//2
outStream.write(buffer,0,lengt)
}
byte[] b= outStream.toByteArray();
String s=new String(b);
return s;
}
如上所示了:注释1和2处
这样写为什么会出现java.lang.OutOfMemoryError
是内存溢出吧!
我修改1,2处:如下:3,4
public String readFile(String fileName) throws Exception{
ByteArrayOutputStream outStream=new ByteArrayOutputStream();
FileInputStream fis=context.openFileInput(fileName);
byte [] buffer=new byte[1024];
int length=0;//3
while((length = fis.read(buffer)) != -1){//4
outStream.write(buffer,0,lengt)
}
byte[] b= outStream.toByteArray();
String s=new String(b);
return s;
}
这样就没有问题了。真心求解释!
Android:
public String readFile(String fileName) throws Exception{
ByteArrayOutputStream outStream=new ByteArrayOutputStream();
FileInputStream fis=context.openFileInput(fileName);
byte [] buffer=new byte[1024];
int length=fis.read(buffer);//1
while(length != -1){//2
outStream.write(buffer,0,lengt)
}
byte[] b= outStream.toByteArray();
String s=new String(b);
return s;
}
如上所示了:注释1和2处
这样写为什么会出现java.lang.OutOfMemoryError
是内存溢出吧!
我修改1,2处:如下:3,4
public String readFile(String fileName) throws Exception{
ByteArrayOutputStream outStream=new ByteArrayOutputStream();
FileInputStream fis=context.openFileInput(fileName);
byte [] buffer=new byte[1024];
int length=0;//3
while((length = fis.read(buffer)) != -1){//4
outStream.write(buffer,0,lengt)
}
byte[] b= outStream.toByteArray();
String s=new String(b);
return s;
}
这样就没有问题了。真心求解释!
解决方案 »
- 关于Hibernate的懒加载,我只想单纯的获取外键值,而不想全部加载,怎么破?
- 求救:spring aop事务配置 出错不回滚
- Struts2注解引发堆栈问题。求高手指教,。。。
- 问大家一个问题
- 求大牛写几段代码
- 我为何总是汉化eclipse-SDK-3.1.1-win32老是不成功啊? 试了好多次了啊!谢谢!急啊!
- 应用struts写的这个简单的jsp文件为什么会报错???
- 大家进来聊聊吧!!!
- 如何在JSP页面显示本地excel文件内容,例如页面上有个显示按钮,点击以后,选择excel文件,就把内容显示到页面上
- javaEE问题求助
- openldap启动报错,麻烦请看看什么原因
- 求Java关于时间的方法
outStream.write(buffer,0,lengt)
}
试试
4这里不是也一直在读吗?4和1的差别在哪里呢?谢谢!
byte [] buffer=new byte[1024];
int length=0;//1
while((length=fis.read(buffer)) != -1){//2
outStream.write(buffer,0,lengt)
}楼主写的代码中,1处虽然执行了一次,但依据楼主的情况该length恒不等于-1,导致2处无限循环,导致不停write,然后溢出。
while(length != -1){//2
outStream.write(buffer,0,lengt)
}这样理解:读了一次,length>-1,
while无限执行!不断写io
public void write(byte[] b,
int off,
int len)
throws IOException
Writes len bytes from the specified byte array starting at offset off to this output stream.