java 读写UTF-8文件的方法
需导入的包:
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.util.List;
java 读写UTF-8文件的方法:
private static void readUtf8File(String fileName) { // 以UTF-8编码读取文件: FileInputStream fis = null; InputStreamReader isr = null; String fileContent = ""; try { fis = new FileInputStream(fileName); isr = new InputStreamReader(fis, "UTF-8"); BufferedReader br = new BufferedReader(isr); String line = null; while ((line = br.readLine()) != null) { fileContent += line; fileContent += "\r\n"; // 补上换行符 } System.out.println(fileContent); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { isr.close(); } catch (IOException e) { e.printStackTrace(); } } }
调用例子:
public static void main(String[] args) throws Exception { // 读取UTF-8文件 readUtf8File("d:\\test.txt"); // 写入UTF-8文件 writeUtf8File("d:\\test1.txt","要写入文件的内容"); }