String s = "";
DataInputStream di2 = new DataInputStream(
new FileInputStream("datatest.txt"));
while( ( s=di2.readUTF() )!=null )
System.out.println( s );
数据读完后结束时抛出异常
请问原因?
另外readUTF如何判断读取到结尾?谢谢~
DataInputStream di2 = new DataInputStream(
new FileInputStream("datatest.txt"));
while( ( s=di2.readUTF() )!=null )
System.out.println( s );
数据读完后结束时抛出异常
请问原因?
另外readUTF如何判断读取到结尾?谢谢~
如果组的第一个字节与位模式 1110xxxx 匹配,则该组由字节 a 和另外两个字节 b 和 c 组成。如果没有字节 c(因为字节 a 是要读取的最后两个字节之一),或者字节 b 或字节 c 与位模式 10xxxxxx 不匹配,则抛出 UTFDataFormatException。否则,将该组转换成字符:
(char)(((a & 0x0F) << 12) | ((b & 0x3F) << 6) | (c & 0x3F))
如果组的第一个字节与模式 1111xxxx 或模式 10xxxxxx 匹配,则抛出 UTFDataFormatException。 如果在执行整个过程中的任意时间遇到文件末尾,则抛出 EOFException。 在通过此过程将每个组转换成字符后,按照从输入流中读取相应组的顺序,将这些字符收集在一起,形成一个 String,然后该字符串将被返回。 可以使用 DataOutput 接口的 writeUTF 方法写入适合此方法读取的数据。 返回:
一个 Unicode 字符串。
抛出:
EOFException - 如果此流在读取所有字节之前到达末尾。
IOException - 如果发生 I/O 错误。
UTFDataFormatException - 如果这些字节不表示一个有效的、UTF-8 修改版编码的字符串。
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
RandomAccessFile fi = new RandomAccessFile("bb.txt", "rw");
String str = null;
while((str=DataInputStream.readUTF( fi )) != null )
System.out.println( "reading from bb " + str );
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}bb.txt是 UTF-8 编码始终在:
while((str=DataInputStream.readUTF( fi )) != null )跳出异常 ,请问原因,
bb.txt文件 中如下内容 :
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="description" content="谢谢各位
EOFException - 如果此输入流在读取所有字节之前到达末尾。
IOException - 如果发生 I/O 错误。
UTFDataFormatException - 如果这些字节不表示一个有效的、UTF-8 修改版编码的字符串这三种异常 根据抛出的异常进行相应的处理
File f = new File(fn);
InputStreamReader read = new InputStreamReader (new FileInputStream(f),"UTF-8");
BufferedReader reader=new BufferedReader(read);
String msg = "";
String info = reader.readLine();
msg = info;
while(true){
info = reader.readLine();
if(info==null) break;
msg = msg + info;
}
return msg;
}//fn 为要读取的文件