大学IT网 - 最懂大学生的IT学习网站! QQ资料交流群:367606806
当前位置:大学IT网 > Java技巧 > java按指定编码写入和读取文件内容的类

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


[摘要]本文主要是对java按指定编码写入和读取文件内容的类的讲解,希望对大家学习java按指定编码写入和读取文件内容的类有所帮助。

  可以指定编码如: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));

  }

  }



相关评论