问一个比较弱的问题

sk811229 2012-08-03 07:10:57
一直以来学习中从来没有操作过中文文件,今天有个事必须要从一个文件中读取中文字符然后输出,才发现束手无策,求助下各位大侠。

先贴下我的范例代码

public static void main(String args[])
{
byte buffer[] = new byte[2056];
try
{
FileInputStream fileint = new FileInputStream("dchs.txt");
int bytes = fileint.read(buffer,0,2056);
String str = new String(buffer,0,0,bytes);
System.out.print(str);
}//try
catch(Exception e)
{
String err = e.toString();
System.out.println(err);
}//cathch
}//public static void main(String args[])


我用 FileInputStream 这么操作 输出的中文总是乱码,英文字符正常。

各位大侠给指教下。
...全文
211 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
xlhb 2012-08-05
  • 打赏
  • 举报
回复
用FileReader。 FileReader 专门用来读取一些纯文本的。 FileInputstream 最底层的一个字节一个字节的读,适合读媒体文件比如图片视频
小文件 2012-08-05
  • 打赏
  • 举报
回复
原来如此啊[Quote=引用 3 楼 的回复:]

这个好说 用FileReader。 FileReader 专门用来读取一些纯文本的。 FileInputstream 最底层的一个字节一个字节的读,适合读媒体文件比如图片视频
[/Quote]
Ada168855 2012-08-05
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 的回复:]
FileInputStream 是字节流,要想操作中文,用FileReader,或将FileInputStream 用InputStreamReader包装,再用BufferedReader缓冲一下。
[/Quote]

不错,这个的确是解决中文乱码的两个方法
AslenG 2012-08-05
  • 打赏
  • 举报
回复
我用下面的方法试了下能读中文。
File file=new File("C:\\dchs.txt");
char[] ch=new char[(int)file.length()];
int len=0;
FileReader fr;
try {
fr = new FileReader(file);
len=fr.read(ch);
System.out.println(new String(ch,0,len));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
}
wwwcomcn123 2012-08-03
  • 打赏
  • 举报
回复
Reader
shoot136464153 2012-08-03
  • 打赏
  • 举报
回复
非要用FileInputStream读 可以用转换流 InputStreamReader 封起来 在用个BufferedReader封起来就好多了
shoot136464153 2012-08-03
  • 打赏
  • 举报
回复
这个好说 用FileReader。 FileReader 专门用来读取一些纯文本的。 FileInputstream 最底层的一个字节一个字节的读,适合读媒体文件比如图片视频
风尘中国 2012-08-03
  • 打赏
  • 举报
回复
在你基础上面改的,不过还是建议使用FileReader类来读文本文件

下面的程序还跟文本文件的编码格式相关,你跑跑看看吧,读的文件名称 你自己改下就好

public class ReadFileDemo {

public static void main(String args[])
{
byte buffer[] = new byte[2056];
try
{
FileInputStream fileint = new FileInputStream("易中天拼三国.txt");
int i=0;
while(fileint.read(buffer)!=-1){
String str=new String(buffer);
System.out.println(str);
}
}//try
catch(Exception e)
{
e.printStackTrace();
String err = e.toString();
System.out.println(err);
}//cathch
}
}
nmyangym 2012-08-03
  • 打赏
  • 举报
回复
FileInputStream 是字节流,要想操作中文,用FileReader,或将FileInputStream 用InputStreamReader包装,再用BufferedReader缓冲一下。

62,621

社区成员

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

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