import java.io.*;
public class InputExa
{ public static void main(String[] args)
{ int b;
byte tom[]=new byte[10];
try
{
File f=new File("G://java code/jackxu/src","WaitExa.java");
FileInputStream in=new FileInputStream(f);
b=in.read(tom);
String s=new String(tom);
b=in.read(tom,0,5);
s=new String(tom);
System.out.println("第一次输出"+s);
}
catch(IOException e)
{ System.out.println("File Read Error"+e);
}
in.close();
}}
上面的程序是读取WaitExa.java文件,把读取的字节转化为字符串输出,b=in.read(tom)这是第一个read()方法,它读取的字节数没确定,就由定义的字节数组确定。b=in.read(tom,0,5);这是第二次使用read()方法,这次规定了字节读取的顺序和长度,结果输出来的还是按第一次byte[10]中输出了10无序字符,这是怎么回事??
public class InputExa
{ public static void main(String[] args)
{ int b;
byte tom[]=new byte[10];
try
{
File f=new File("G://java code/jackxu/src","WaitExa.java");
FileInputStream in=new FileInputStream(f);
b=in.read(tom);
String s=new String(tom);
b=in.read(tom,0,5);
s=new String(tom);
System.out.println("第一次输出"+s);
}
catch(IOException e)
{ System.out.println("File Read Error"+e);
}
in.close();
}}
上面的程序是读取WaitExa.java文件,把读取的字节转化为字符串输出,b=in.read(tom)这是第一个read()方法,它读取的字节数没确定,就由定义的字节数组确定。b=in.read(tom,0,5);这是第二次使用read()方法,这次规定了字节读取的顺序和长度,结果输出来的还是按第一次byte[10]中输出了10无序字符,这是怎么回事??
0是offset,回到tom的位置0从in读5个覆盖掉tom前5位,而tom后5位是第一次读的。
可能碰巧你第一次读的10位的前5位与第二次读的5位一样。
假设你的文件中的字符为abcdefghijklmnopqrst……等
int b;
byte tom[] = new byte[10];
byte tom1[] = new byte[10];
File f = new File("G://java code/jackxu/src","WaitExa.java");
FileInputStream in = null;
try {
in = new FileInputStream(f);
b = in.read(tom);//b等于10
String s = new String(tom);
System.out.println("第一次输出" + s);//输出a~j前面十个
b = in.read(tom1, 0, 5);//b等于5
s = new String(tom1
System.out.println("第二次输出" + s););//输出k~o接着j后面五个。因为数组开辟的空间为十,所以后面再填充五个空格。为什么会接着后面读取,因为你在同一个流中读取的, in.read(tom1, 0, 5),所以j后面肯定读取k,这就是0(当前的下一个)的含义,5就代表读取几个字符。
} catch (IOException e) {
System.out.println("File Read Error" + e);
}finally{
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
如果像你那样只有一个数组,输出的就没有空格,前面5个字符替换掉,后面5个不变。不知道懂不懂,这个东西我也只能说成这样了。