自动识别编码读取和写入文件

来源:互联网 发布:微云for mac 编辑:程序博客网 时间:2024/06/09 22:46
public class FileTraning {

/**
* 判断文件的编码格式
* @param fileName :file
* @return 文件编码格式
* @throws Exception
*/
public static String codeString(String fileName) throws Exception{
BufferedInputStream bin = new BufferedInputStream(
new FileInputStream(fileName));
int p = (bin.read() << 8) + bin.read();
String code = null;

switch (p) {
case 0xefbb:
code = "UTF-8";
break;
case 0xfffe:
code = "Unicode";
break;
case 0xfeff:
code = "UTF-16BE";
break;
default:
code = "GBK";
}
return code;
}

public static String readFile(String filePathAndName,String code) {
 String fileContent = "";
 try {  
  File f = new File(filePathAndName);
  if(f.isFile()&&f.exists()){
   InputStreamReader read = new InputStreamReader(new FileInputStream(f),code);
   BufferedReader reader=new BufferedReader(read);
   String line;
   while ((line = reader.readLine()) != null) {
    fileContent += line;
   }   
   read.close();
  }
 } catch (Exception e) {
  System.out.println("读取文件内容操作出错");
  e.printStackTrace();
 }
 return fileContent;
}

public static void writeFile(String filePathAndName, String fileContent, String code) {
 try {
  File f = new File(filePathAndName);
  if (!f.exists()) {
   f.createNewFile();
  }
  OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f),code);
  BufferedWriter writer=new BufferedWriter(write);   


  writer.write(fileContent);
  writer.close();
 } catch (Exception e) {
  System.out.println("写文件内容操作出错");
  e.printStackTrace();
 }
}

public static void main(String[] args) {
String fileName = "c:/1.txt";
String code = "";
try {
code = codeString(fileName);
System.out.println(code);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(readFile(fileName,code));
writeFile(fileName,"中文测试修改内容",code);
}
}
0 0
原创粉丝点击