注册 登录
编程论坛 JAVA论坛

关于I/O流的一个小问题

cpxuvs 发布于 2015-12-23 20:10, 2575 次点击

程序代码:
import *;
public class Text
{
    public static void main(String[] args) throws IOException
    {
        try
        {
        FileInputStream fis =new FileInputStream("Text.java");
        byte[]b=new byte[1024];
        int hasRead=0;
        while((hasRead=fis.read(b))>0)//请问一下,这里为什么要将fis.read(b)赋给一个int变量,直接写fis.read(b)>0的话会报错
        {
            System.out.print(new String(b,0,hasRead));//如果上面只写fis.read(b)>0的话,这里也要改
        }
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        
        
    }
   
}
8 回复
#2
林月儿2015-12-23 20:44
!=-1
#3
limingcong012015-12-23 21:16
这个是一个方法 , 返回值是一个int类型 ,所以一定要用int类型才能接收,不能直接声明
#4
cpxuvs2015-12-24 15:05
没看懂,难道有返回值的方法一定要接受一个对应类型的变量吗
#5
xww35829812015-12-24 21:02
#6
youfgd3332015-12-25 00:03
你的意思是这样的代码么?
程序代码:

try {
            FileInputStream fis = new FileInputStream("Text.txt");
            byte[] b = new byte[1024];
            while (fis.read(b)> 0)// fis.read()有个读的操作,这样的话读了两遍了.
            {
                System.out.print(new String(b, 0, fis.read(b)));// 这边需要用到读取的长度,里面的最后一次是-1,会报错
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
#7
cpxuvs2015-12-25 20:30
懂了,多谢
#8
crazyman282015-12-29 16:43
read方法,读到末尾的返回值是-1.
 System.out.print(new String(b,0,fis.read()));  
这段代码会报错:java.lang.StringIndexOutOfBoundsException: String index out of range: -1
#9
q5147005482015-12-30 06:43
怎么结贴啊?
1