如何读取一个文件,用某种特定的编码写入另一个文件(JAVA)

2024-12-03 03:41:32
推荐回答(2个)
回答1:

import java.io.File;
import java.io.IOException;

public class CovertEncode {
public static void main(String args[]) throws Exception {
CovertFile("d:\\1.txt");
}

public static void CovertFile(String filename) throws IOException {

String backupfilename = filename + ".backup";
File f = new File(filename);
File outf = new File(backupfilename);
f.renameTo(outf);

java.io.FileInputStream in = new java.io.FileInputStream(backupfilename);
java.io.InputStreamReader isr = new java.io.InputStreamReader(in, "Big5");
java.io.BufferedReader br = (new java.io.BufferedReader(isr));

// open output stream
java.io.FileOutputStream out = new java.io.FileOutputStream(filename);
java.io.BufferedWriter bw = new java.io.BufferedWriter(
new java.io.OutputStreamWriter(out, "GBK"));

char[] buffer = new char[4096];
int len;
while ((len = br.read(buffer)) != -1)
bw.write(buffer, 0, len);
br.close();
bw.flush();
bw.close();
outf.deleteOnExit();
}
}

回答2:

用ByteArrayInputStream或ByteBufferInputStream。