求助, 关于文件读取并显示的问题

bjzxg 2004-08-25 03:14:34
import java.io.*;




public class temp{





public static void main(String args[]){
int read;
byte[] buffer;
String s;


try{ File f = new File("d:\\1.txt");
File f2 = new File("d:\\zxg.txt");


FileInputStream in = new FileInputStream(f);
DataInputStream dis = new DataInputStream(in);
//FileOutputStream out = new FileOutputStream(f2);
//DataOutputStream dos = new DataOutputStream(out);

do {
buffer = new byte[512];
read = dis.read(buffer);
if( read!=-1){
//dos.write(buffer);
s = new String(buffer,0,read);

System.out.println(s);
}
} while(read!= -1);

dis.close();
}
catch (Exception e) {System.out.println(e.toString());}
}

}



上面这段代码,如果是读取后写入文件里,则2个文件的内容一致

如果是像上面这样,用System.out.println打印,则有问题: 文件的前面总是打印不出来。
试了许多文件,都是这种情况。 究竟问题出在哪里??
...全文
131 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
jackkui 2004-08-25
  • 打赏
  • 举报
回复
FileInputStream和FileOutputStream
是按字节进行读写的,所以
有些特殊字符的显示可能会出现错误
如果你是*.txt文件可以
用BufferedReader,BufferedWriter或者
FileReader和FileWriter这些都是字符方式读写的。
bjzxg 2004-08-25
  • 打赏
  • 举报
回复
老大,能告诉我怎么解决马?

程序运行时,在前几次读取时,读入到String s = new String(buffer,0,read),此时String s的长度是0。 也就是说,没有任何内容读入。
但是那个dis.read(buffer)却继续读了下去。我该怎么办>?
njuabc 2004-08-25
  • 打赏
  • 举报
回复
因为你文件里面含有一些特殊字符,
这些特殊字符无法用String来表示,
String里面放的其实是一个个char,

62,622

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧