您好,欢迎访问一九零五行业门户网

java读写html文件乱码解决方法

1、java读取文件,避免中文乱码。
/** * 读取文件内容 * * @param filepathandname * string 如 c:\\1.txt 绝对路径 * @return boolean */public static string readfile(string filepathandname) { string filecontent = ""; try { file f = new file(filepathandname); if(f.isfile()&&f.exists()){ inputstreamreader read = new inputstreamreader(new fileinputstream(f),"utf-8"); bufferedreader reader=new bufferedreader(read); string line; while ((line = reader.readline()) != null) { filecontent += line+"\n"; } read.close(); } } catch (exception e) { system.out.println("读取文件内容操作出错"); e.printstacktrace(); } return filecontent;}
2、java写入文件,避免中文乱码。
public static void writefile(string filepathandname, string filecontent) { try { file f = new file(filepathandname); if (!f.exists()) { f.createnewfile(); } outputstreamwriter write = new outputstreamwriter(new fileoutputstream(f),"utf-8"); bufferedwriter writer=new bufferedwriter(write); //printwriter writer = new printwriter(new bufferedwriter(new filewriter(filepathandname))); //printwriter writer = new printwriter(new filewriter(filepathandname)); writer.write(filecontent); writer.close(); } catch (exception e) { system.out.println("写文件内容操作出错"); e.printstacktrace(); }}
若写入的时候用 
1、printwriter writer = new printwriter(new bufferedwriter(new filewriter(filepathandname))); 
2、printwriter writer = new printwriter(new filewriter(filepathandname)); 
都会出现错误,不行。 
p.s. 我刚开始用上述方法的时候还是出先乱码,后来发现是因为我的html文件的编码方式是不是utf-8,改成utf-8即可。
查看一个文件的编码方式,一个简单的办法是:用记事本打开它,然后另存为一个副本文件,在“另存为”的页面下方,“保存”按钮前面,如下图所示,会出现原文件的编码方式。
如果不是utf-8,把它改成utf-8,保存即可。
更多java知识请关注java基础教程栏目。
以上就是java读写html文件乱码解决方法的详细内容。
其它类似信息

推荐信息