/** * * @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 write = new outputstreamwriter(new fileoutputstream(f), utf-8);
outputstreamwriter是从字符流到字节流的桥接:使用指定的字符集将写入其中的字符编码为字节。它使用的字符集可以通过名称指定,也可以明确指定,或者可以接受平台的默认字符集。
每次调用write()方法都会导致在给定字符上调用编码转换器。生成的字节在写入底层输出流之前在缓冲区中累积。可以指定此缓冲区的大小,但默认情况下,它足够大,可用于大多数用途。请注意,传递给write()方法的字符不会被缓冲。
outputstreamwriter流中的构造方法可以指定字符集,或者不设置取默认值。
更多java知识请关注java基础教程栏目。
以上就是java写入文件乱码怎么解决的详细内容。
