java按指定编码写入和读取文件内容的类分享

时间:2022-03-28 09:52:15

可以指定编码如:utf-8来写入和读取文件。如果文件编码未知,可以通过该方法先得到文件的编码后再指定正确的编码来读取,否则会出现文件乱码问题。

如何识别文件编码请参考:java自动根据文件内容的编码来读取避免乱码

 

复制代码代码如下:


package com.zuidaima.util;

 

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class ReadWriteFileWithEncode {

 public static void write(String path, String content, String encoding)
   throws IOException {
  File file = new File(path);
  file.delete();
  file.createNewFile();
  BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
    new FileOutputStream(file), encoding));
  writer.write(content);
  writer.close();
 }

 public static String read(String path, String encoding) throws IOException {
  String content = "";
  File file = new File(path);
  BufferedReader reader = new BufferedReader(new InputStreamReader(
    new FileInputStream(file), encoding));
  String line = null;
  while ((line = reader.readLine()) != null) {
   content += line + "\n";
  }
  reader.close();
  return content;
 }

 public static void main(String[] args) throws IOException {
  String content = "中文内容";
  String path = "c:/test.txt";
  String encoding = "utf-8";
  ReadWriteFileWithEncode.write(path, content, encoding);
  System.out.println(ReadWriteFileWithEncode.read(path, encoding));
 }
}