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

java读写乱码解决方法

java读写乱码解决方法:
1、读文件:
/** * 读取文件内容 * * @param filepathandname * string 如 c:\\1.txt 绝对路径 * @return boolean */ public static string readfile(string filepath) { string filecontent = ""; try { file f = new file(filepath); 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; } read.close(); } } catch (exception e) { system.out.println("读取文件内容操作出错"); e.printstacktrace(); } return filecontent; }
inputstreamreader类是从字节流到字符流的桥接器:它使用指定的字符集读取字节并将它们解码为字符。 它使用的字符集可以通过名称指定,也可以明确指定,或者可以接受平台的默认字符集。
2、写文件
/** * * @title: writefile * @description: 写文件 * @param @param filepath 文件路径 * @param @param filecontent 文件内容 * @return void 返回类型 * @throws */ public static void writefile(string filepath, string filecontent) { try { file f = new file(filepath); if (!f.exists()) { f.createnewfile(); } outputstreamwriter write = new outputstreamwriter(new fileoutputstream(f), "utf-8"); bufferedwriter writer = new bufferedwriter(write); writer.write(filecontent); writer.close(); } catch (exception e) { system.out.println("写文件内容操作出错"); e.printstacktrace(); } }
outputstreamwriter是从字符流到字节流的桥接:使用指定的字符集将写入其中的字符编码为字节。它使用的字符集可以通过名称指定,也可以明确指定,或者可以接受平台的默认字符集。
更多java知识请关注java基础教程栏目。
以上就是java读写乱码解决方法的详细内容。
其它类似信息

推荐信息