前言: IT培训网小编来告诉大家java读写文件出现乱码的解决方法。 1.读文件: /*** 读取文件内容* @param filePathAndName* String 如
IT培训网小编来告诉大家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是从字符流到字节流的桥接:使用指定的字符集将写入其中的字符编码为字节。它使用的字符集可以通过名称指定,也可以明确指定,或者可以接受平台的默认字符集。
文章出自:http://qh.itpxw.cn/peixun/software/2022121611.html
文章标题:Java读取文件出现乱码的解决方法
免责声明:本站文章均由入驻起航学习网的会员所发或者网络转载,所述观点仅代表作者本人,不代表起航学习网立场。如有侵权或者其他问题,请联系举报,必删。侵权投诉
IT培训网 访问该机构站点 报名留言 加为好友 用户等级:注册会员
用户级别:10
机构名称:IT培训网
联 系 人:罗老师
联系电话:13783581536
联系手机:13783581536
在线客服:
在 线 QQ:
电子邮件:
网站域名:http://www.itpxw.cn
注册时间:2016-07-18 11:07
最后登录:2024-02-20 13:02
Java定义方法的格式是什么?IT培训网小编来告诉大家。所谓方法...
大家在Java教程中会学到关于Java消息推送的知识,那么,Java消息...
常用的Java日期格式转换有哪些?IT培训网小编来告诉大家。 1...
Java创建对象数组的方法是什么?IT培训网小编来告诉大家。Ja...