当前位置: 技术问答>java相关
文件操作问题? please help:)
来源: 互联网 发布时间:2015-04-13
本文导语: 我想读取磁盘上的一个文件,然后将读入的文件以UNICODE方式写入磁盘,一个字符两字节写入,我用FileWriter将文件以字符的方式读入,用FileWriter将字符直接写入磁盘时,原来的非双字节字符还是以原来的形式写入,并...
我想读取磁盘上的一个文件,然后将读入的文件以UNICODE方式写入磁盘,一个字符两字节写入,我用FileWriter将文件以字符的方式读入,用FileWriter将字符直接写入磁盘时,原来的非双字节字符还是以原来的形式写入,并没有扩展为双字节字符,我想将读入的字符全部转换为双字节的,但是不知道怎么转换。
请问有什么好的方法执行这一操作吗?
请问有什么好的方法执行这一操作吗?
|
public String readFile(String filename) throws Exception
{
//Read the file into a string buffer, then return as a string.
StringBuffer buf;//the intermediary, mutable buffer
BufferedReader breader;//reader for the template files
try
{
breader = new BufferedReader(new FileReader(filename));//header
buf = new StringBuffer();
while(breader.ready())
buf.append((char)breader.read());
breader.close();
}//try
catch(Exception e)
{
throw e;
}//catch
return buf.toString();
}//readFile
public void writeFile(String str, String filename) throws Exception
{
// Open a writer to the file, then write the string.
BufferedWriter bwriter;//writer to the file
String fullfilepath;//path for the output file
try
{
bwriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename)));
bwriter.write(str);
bwriter.flush();
bwriter.close();
}//try
catch(Exception e)
{
throw e;
}//catch
}//writeFile
{
//Read the file into a string buffer, then return as a string.
StringBuffer buf;//the intermediary, mutable buffer
BufferedReader breader;//reader for the template files
try
{
breader = new BufferedReader(new FileReader(filename));//header
buf = new StringBuffer();
while(breader.ready())
buf.append((char)breader.read());
breader.close();
}//try
catch(Exception e)
{
throw e;
}//catch
return buf.toString();
}//readFile
public void writeFile(String str, String filename) throws Exception
{
// Open a writer to the file, then write the string.
BufferedWriter bwriter;//writer to the file
String fullfilepath;//path for the output file
try
{
bwriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename)));
bwriter.write(str);
bwriter.flush();
bwriter.close();
}//try
catch(Exception e)
{
throw e;
}//catch
}//writeFile
|
把楼上的改一下,生成OutputStreamWriter时加上字符编码:
bwriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename)));
改成
bwriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename), "utf-8"));
注意,Unicode的双字节表现形式不止一种,请注意Unicode与其表现形式的区别。
bwriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename)));
改成
bwriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename), "utf-8"));
注意,Unicode的双字节表现形式不止一种,请注意Unicode与其表现形式的区别。