展开全部
package test;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class ConvertCharset
{
/**
* @param path the file path or directory
* @param back the backup file path or directory
* @param cs1 the orignle charset name
* @param cs2 the dest charset to convert
*/
public static void convertCharset ( String path, String back, String cs1, String cs2 )
{
32313133353236313431303231363533e78988e69d8331333335336434try
{
String separator = System.getProperty ("line.separator");
File dir = new File (path);
// a directory, not a file
if (dir.isDirectory ())
{
File[] files = dir.listFiles ();
for ( int i = 0; i
{
File dirt = files[i];
String fn = dirt.getName ();
String name = path + File.separator + fn;
// recursion
if (dirt.isDirectory ())
{
convertCharset (name, back + File.separator + fn, cs1, cs2);
}
else
{
// write
File dest = new File(back);
if (!dest.exists ())
{
dest.mkdirs ();
}
FileOutputStream fos = new FileOutputStream (back + File.separator + fn);
OutputStreamWriter osw = new OutputStreamWriter (fos, cs2);
BufferedWriter bw = new BufferedWriter (osw);
// read
FileInputStream fis = new FileInputStream (name);
InputStreamReader isr = new InputStreamReader (fis, cs1);
BufferedReader br = new BufferedReader (isr);
String line = null;
while (null != ( line = br.readLine () ))
{
bw.write (line + separator);
}
// write
fos.flush ();
osw.flush ();
bw.flush ();
bw.close ();
osw.close ();
fos.close ();
// read
br.close ();
isr.close ();
fis.close ();
}
}
}
// a single file
else
{
// write
File dest = new File(back);
if (!dest.exists ())
{
dest.mkdir ();
}
FileOutputStream fos = new FileOutputStream (back + File.separator + dir.getName ());
OutputStreamWriter osw = new OutputStreamWriter (fos, cs2);
BufferedWriter bw = new BufferedWriter (osw);
// read
FileInputStream fis = new FileInputStream (path);
InputStreamReader isr = new InputStreamReader (fis, cs1);
BufferedReader br = new BufferedReader (isr);
String line = null;
while (null != ( line = br.readLine () ))
{
bw.write (line + separator);
}
// write
fos.flush ();
osw.flush ();
bw.flush ();
bw.close ();
osw.close ();
fos.close ();
// read
br.close ();
isr.close ();
fis.close ();
}
System.out.println ("Convert Success !");
}
catch (Exception e)
{
e.printStackTrace ();
}
}
public static void main ( String[] args )
{
// a single file
convertCharset ("I:\\2013313workspace\\Yaojiangji\\src\\yaojiangji\\paixu.java",
"I:\\2013313workspace\\Yaojiangji\\back",
"GBK",
"UTF-8");
// not a file , it's a directory
//convertCharset ("I:\\2013313workspace\\Yaojiangji\\src\\yaojiangji",
// "I:\\2013313workspace\\Yaojiangji\\back\\yaojiangji",
// "GBK",
// "UTF-8");
}
}