java按指定编码写入和读取文件内容的类分享
可以指定编码如:utf-8来写入和读取文件。如果文件编码未知,可以通过该方法先得到文件的编码后再指定正确的编码来读取,否则会出现文件乱码问题。
如何识别文件编码请参考:java自动根据文件内容的编码来读取避免乱码
package com.zuidaima.util;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class ReadWriteFileWithEncode {
public static void write(String path, String content, String encoding)
throws IOException {
File file = new File(path);
file.delete();
file.createNewFile();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file), encoding));
writer.write(content);
writer.close();
}
public static String read(String path, String encoding) throws IOException {
String content = "";
File file = new File(path);
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(file), encoding));
String line = null;
while ((line = reader.readLine()) != null) {
content += line + "\n";
}
reader.close();
return content;
}
public static void main(String[] args) throws IOException {
String content = "中文内容";
String path = "c:/test.txt";
String encoding = "utf-8";
ReadWriteFileWithEncode.write(path, content, encoding);
System.out.println(ReadWriteFileWithEncode.read(path, encoding));
}
}
上一篇:java实现图片上加文字水印(SpringMVC + Jsp)
栏 目:JAVA代码
下一篇:scala中常用特殊符号详解
本文地址:http://www.codeinn.net/misctech/17642.html
阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机