Есть файл.txt з данными подскажите как в java поменять кодировку этого файла.
1 ответ
Хотя это немного и противоречит правилам форума, все же выдам из запасников:
/**
* More or less universal codepage convertor
* @param infile - input file name, if null System.in presumed
* @param outfile - output file name, if null System.out presumed
* @param from - input file codepage as of http://www.iana.org/assignments/character-sets, if null system wide property assumed
* @param to - output file codepage as of http://www.iana.org/assignments/character-sets, if null system wide property assumed
* @throws IOException if something wrong with files
* @throws UnsupportedEncodingException if system doesn't support specified codepage
*/
public static void convert(String infile, String outfile, String from, String to)
throws IOException, UnsupportedEncodingException
{
// set up byte streams
InputStream in;
if(infile != null)
in=new FileInputStream(infile);
else
in=System.in;
OutputStream out;
if(outfile != null)
out=new FileOutputStream(outfile);
else
out=System.out;
// Use default encoding if no encoding is specified.
if(from == null) from=System.getProperty("file.encoding");
if(to == null) to=System.getProperty("file.encoding");
// Set up character stream
Reader r=new BufferedReader(new InputStreamReader(in, from));
Writer w=new BufferedWriter(new OutputStreamWriter(out, to));
// Copy characters from input to output. The InputStreamReader
// converts from the input encoding to Unicode,, and the OutputStreamWriter
// converts from Unicode to the output encoding. Characters that cannot be
// represented in the output encoding are output as '?'
char[] buffer=new char[4096];
int len;
while((len=r.read(buffer)) != -1)
w.write(buffer, 0, len);
r.close();
w.flush();
w.close();
}
Пример вызова (перекодировка из традиционной китайской в UTF-8):
convert("chinese-traditional.txt", "chinese-utf-8.txt", "GB2312", "UTF8");