java读取、写入(读写)txt文件中文乱码问题(相对应编码)
编码:将txt默认的ANSI转为其它格式
打开txt文件,另存为,选择编码方式
读写文件源码:
public static void main(String[] args) {
String encoding="Unicode"; //字符编码
try{
File readFile=new File("studentInfo.txt.txt"),
writeFile=new File("studentName.txt");//studentInfo.txt.txt初始编码为Unicode
//if(readFile.isFile()&&readFile.exists())
//{
//读取txt文件时的txt的原始编码格式
InputStreamReader inOne = new InputStreamReader(new FileInputStream(readFile),encoding);
BufferedReader inTwo=new BufferedReader(inOne);
//BufferedReader inTwo=new BufferedReader(new InputStreamReader(new FileInputStream(readFile),encoding));
//FileWriter tofile=new FileWriter("studentName.txt");
OutputStreamWriter tofile = new OutputStreamWriter(new FileOutputStream(writeFile),"gbk");
BufferedWriter out=new BufferedWriter(tofile);
//BufferedWriter out =new BufferedWriter(new OutputStreamWriter(new FileOutputStream(writeFile),encoding));
String s;
int i=0;
while((s=inTwo.readLine())!=null)
{
i++;
out.write("("+i+")"+""+s);
out.newLine();
}
out.flush();
out.close();
inTwo.close();
//tofile.close();
inTwo=new BufferedReader(new FileReader("studentName.txt"));
while((s=inTwo.readLine())!=null)
{
System.out.println(s);
}
}
//}
catch(IOException e){
e.printStackTrace();
}
}studentInfo.txt.txt文件的初始编码为Unicode那么读取文件时InputStreamReader inOne = new InputStreamReader(new FileInputStream(readFile),encoding);的encoding定义的也是Unicode,如果是别的编码格式也要对应。此时不论写入是用的什么编码艘恢新建成你写入时用的编码格式的studentName文件,但如果你要在eclipse上显示输出,由于默认的是gbk,所以你的写入也应该是gbk格式OutputStreamWriter tofile = new OutputStreamWriter(new FileOutputStream(writeFile),"gbk");
改变eclipse的默认编码方式(UTF-8)
以下转http://www.cnblogs.com/smartdog/archive/2011/05/23/2054602.html
1、windows->Preferences...打开"首选项"对话框,general->Workspace,右侧 Text file encoding,选择Other,改变为UTF-8,以后新建立工程其属性对话框中的Text file encoding即为UTF-8。
2、windows->Preferences...打开"首选项"对话框,general->Content Types,右侧Context Types,点开Text,选择Java Source File,在下面的Default encoding输入框中输入UTF-8,点Update,则设置Java文件编码为UTF-8。其他java应用开发相关的文件如:properties、XML等已经由Eclipse缺省指定,分别为ISO8859-1,UTF-8,如开发中确需改变编码格式则可以在此指定。
3、经过上述两步,新建java文件即为UTF-8编码,Eclipse编译、运行、调试都没问题,但是做RCP应用的Product输出时、或者插件输出时,则总是出错,要么不能编译通过(输出时要重新compile)、要么输出的插件运行时中文显示乱码。此时需要再RCP应用、或插件 Plugin工程的build.properties中增加一行,javacDefaultEncoding.. = UTF-8。让输出时编译知道java源文件时UTF-8编码。这个设置需要保证所有的java源文件时UTF-8编码格式,如果不全是,可以参考 Eclipse帮中(Plug-in Development Environment Guide > Reference > Feature and Plug-in Build configuration),建议全部java源文件是UTF-8编码。
如果插件开发、RCP应用开发原来基于其他编码,如GB18030,想转换为UTF-8,则首先,做以上工作;然后通过查找编码转换工具,如基于 iconv的批量转换工具,将原编码转换为UTF-8编码,注意只转换java源文件,其他类型文件可能已经是比较合适的编码了;将原工程属性中的 Text file encoding,从原编码改为UTF-8即可。
本文介绍了Java在读写txt文件时遇到的中文乱码问题,强调了转换文件编码的重要性,如从ANSI转为UTF-8。同时,详细阐述了如何更改Eclipse的工作区和特定文件类型的默认编码,确保新创建的Java文件使用UTF-8编码。此外,对于RCP应用和插件开发,文中提到了在build.properties中设置javacDefaultEncoding为UTF-8以避免编译和运行时的乱码问题。
1469

被折叠的 条评论
为什么被折叠?



