Review before trying java.nio.file.Files (because I haven't done it recently ...).
FileInputOutput.java
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 FileInputOutput {
/**
*File read / write sample.<br>
*Read a file and write it to another file.<br>
*The input file is SJIS.<br>
*Output file is UTF-8(With BOM)
*
* @param args
*/
public static void main(String args[]) throws Exception {
BufferedReader br = null;
BufferedWriter bw = null;
try {
//File reading
//
File inFile = new File("D:/", "input.csv");
br = new BufferedReader(new InputStreamReader(new FileInputStream(
inFile), "SJIS"));
//File output stream
File outFile = new File("D:/", "output.csv");
FileOutputStream os = new FileOutputStream(outFile);
//Grant BOM.
os.write(0xef);
os.write(0xbb);
os.write(0xbf);
//Generate BufferedWriter
bw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
String str;
//Write to file
while ((str = br.readLine()) != null) {
bw.write(str + "\n");
}
//File deletion(You can delete the read file by uncommenting it.)
// inFile.delete();
br.close();
bw.close();
} finally {
if (br != null) {
br.close();
}
if (bw != null) {
bw.close();
}
}
}
}
The contents of the input file could be output in UTF-8 (with BOM) properly.
Recommended Posts