package com.hpli.demo;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class FileUtil {
/**
* 根据编码集创建
* @param file
* @param content
* @param encodType
* @throws IOException
*/
public static void createFile(String file, String content, String encodType)
throws IOException {
FileOutputStream writerStream = new FileOutputStream(file);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
writerStream, encodType));
writer.write(content);
writer.close();
}
/**
* 读取文件内容
* @param file
* @param encodType
* @return
* @throws IOException
*/
public static String getContent(String file, String encodType)
throws IOException {
//"xx\r\n" read -> "xx"
StringBuffer content = new StringBuffer();
FileInputStream fis = new FileInputStream(file);
DataInputStream dis = new DataInputStream(fis);
BufferedReader br = new BufferedReader(new InputStreamReader(dis,
encodType));
String line = null;
if((line = br.readLine()) != null){
content.append(line);
}
while ((line = br.readLine()) != null) {
content.append("\r\n" + line);
}
br.close();
dis.close();
fis.close();
return content.toString();
}
public static void main(String[] args) throws IOException {
String str = "耦嬡沵哋 尒尒婀焱暒妏恻鉽嗵過";
createFile("F:/cnt1.txt", str, "UTF-8");
createFile("F:/cnt2.txt", str, "GBK");
String con1 = getContent("F:/cnt1.txt", "UTF-8");
System.out.println(con1);
String con2 = getContent("F:/cnt2.txt", "GBK");
System.out.println(con2);
}
}
分享到:
相关推荐
在工作中经常读写文本文件,在读文件时,需要按开头的两个字节判断文件格式,然后按该格式读文件中的内容。 写文件时,也要按目标文件指定的格式来写入,只有这样才能让后续的环境正确读入。 1 查看格式 在vs...
Delphi读写UTF-8、Unicode格式文本文件 .mht
香农编码,信息论与编码课程实验,纯C程序,能读写文件
文件读写;;按数据的组织形式不同,可以将文件分为文本文件和二进制文件两大类。 文本文件一般由单一特定编码的字符组成。 二进制文件直接由比特0和比特1组成。;Python对文本文件和二进制文件采用统一的操作步骤: ...
Java实现对文件的读写,可设置编码格式
INI文件格式及其读写相关内容
NULL 博文链接:https://sanry.iteye.com/blog/2297657
简单的filestream的应用实例,说明了他对文件的读写过程。
今天小编就为大家分享一篇python 读写文件包含多种编码格式的解决方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
C语言写的读取INI信息例程,对自己的ini文件操作的Api例程.GetiniString_App
于是在网上搜索了一下,结果发现很多人说FSO只能写ANSI编码的文件,不能写utf-8格式的文件,并且只能读写文本文件。很多人都选择用ADODB.STREAM对象来替代FSO对象,因为STREAM类有LOADFROMFILE和SAVETOFILE方法.并且...
python中读写文件及中文编码处理方法.docx
代码详细描述了通过java读写xml文件的方法,值得一看
NULL 博文链接:https://fengfan2008.iteye.com/blog/426137
有了这个 就可以用最基本的fopen fwrite读写Tiff了。
C# 生成xml文件,编码为utf-8方法
Java实现对文件的读写,可设置编码格式
使用vbs读写文件(Adodb.Stream)方式,防止乱码