java读写php文件,java和php文件读写对比举例及解决让人头痛的乱码问题

JAVA文件读写必须要注意编码问题

java的文件写

直接使用FileWriter即可,第二个参数为追加写入,默认是覆盖写。写完必须close才会保存写好的内容。

默认情况如果没有会新建一个文件

FileWriter fw = null;

try {

fw = new FileWriter("/data/updatetime.dat", true); // true追加写入

fw.append(message + "\n\r");

} catch (IOException e) {

e.printStackTrace();

} finally {

if (fw != null) {

try {

fw.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

java的文件读

FileReader直接读中文会有乱码问题

FileReader fr = new FileReader("/data/updatetime.dat");

char[] data = new char[1024];

int num = fr.read(data);

String result = new String(data, 0, num);

//这里会产生乱码问题

使用输入流转字符读同样会产生乱码(汗),仔细分析原因,如果文件保存是ANSI编码的(FileWriter写入默认是此编码),那么这里必须是iso8859-1,并且需要转换。

String r = null;

try {

BufferedReader br;

br = new BufferedReader(new InputStreamReader(new FileInputStream("/data/updatetime.dat"), "iso8859-1"));

String line = null;

StringBuffer result = new StringBuffer();

while((line = br.readLine()) != null) {

result.append(line);

}

br.close();

r = result.toString();

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

System.out.println(r);

//这里同样会有乱码问题

下面是不会乱码的的方式

如果数据文件为ANSI编码(默认)

BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("/data/updatetime.dat"), "iso8859-1"));

String line = null;

StringBuffer result = new StringBuffer();

while((line = br.readLine()) != null) {

result.append(line + "
");

}

br.close();

String r = new String(result.toString().getBytes("iso8859-1"), "utf-8");

System.out.println(r);

如果数据文件为UTF-8编码

Bu

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值