问题一:以下的代码运行后,会多输一些东西了,看了就知道,这是什么原因,是因为所开的缓冲区buffer小了吗?我试过将buffer加大为1024就正常啦。
问题二:如何获取文件的长度-。-
import java.io.*;
public class OpenFile
{
private String fileName="OpenFile";
//private File file;
public static void main(String args[]) throws IOException
{
try
{
FileInputStream rf=new FileInputStream("OpenFile.java");
int n=512;
//file=new File(fileName);
//file.length();
byte buffer[]=new byte[n];
while((rf.read(buffer,0,n)!=-1)&&(n>0))
{
System.out.print(new String(buffer));
}
System.out.println();
rf.close();
}
catch(IOException ioe)
{
System.out.println(ioe);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
问题二:如何获取文件的长度-。-
import java.io.*;
public class OpenFile
{
private String fileName="OpenFile";
//private File file;
public static void main(String args[]) throws IOException
{
try
{
FileInputStream rf=new FileInputStream("OpenFile.java");
int n=512;
//file=new File(fileName);
//file.length();
byte buffer[]=new byte[n];
while((rf.read(buffer,0,n)!=-1)&&(n>0))
{
System.out.print(new String(buffer));
}
System.out.println();
rf.close();
}
catch(IOException ioe)
{
System.out.println(ioe);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
{
System.out.print(new String(buffer));
}
改为while((int b=rf.read(buffer,0,n)!=-1)&&(n>0))
{
System.out.print(new String(buffer,0,b));
}
{
System.out.print(new String(buffer,0,b));
}
改成
while((rf.read(buffer,0,n)!=-1)&&(n>0))
{
System.out.print(new String(buffer));
buffer = new byte[n] ;
}就可以了.
2:rf.available()可以获得文件的长度.
{
System.out.print(new String(buffer));
}
改为
int b;
while(( b=rf.read(buffer,0,n)!=-1)&&(n>0))
{
System.out.print(new String(buffer,0,b));
}
就可以了.