国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

java按指定編碼寫入和讀取文件內(nèi)容的類分享

2019-11-26 15:41:11
字體:
供稿:網(wǎng)友

可以指定編碼如:utf-8來寫入和讀取文件。如果文件編碼未知,可以通過該方法先得到文件的編碼后再指定正確的編碼來讀取,否則會出現(xiàn)文件亂碼問題。

如何識別文件編碼請參考:java自動(dòng)根據(jù)文件內(nèi)容的編碼來讀取避免亂碼

復(fù)制代碼 代碼如下:

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 = "中文內(nèi)容";
  String path = "c:/test.txt";
  String encoding = "utf-8";
  ReadWriteFileWithEncode.write(path, content, encoding);
  System.out.println(ReadWriteFileWithEncode.read(path, encoding));
 }
}

發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 大港区| 邹城市| 镇坪县| 辉县市| 新营市| 读书| 关岭| 阿拉尔市| 色达县| 临海市| 易门县| 酉阳| 疏附县| 汉沽区| 深州市| 武城县| 赤水市| 绥棱县| 定边县| 麻江县| 壶关县| 曲麻莱县| 沙河市| 秭归县| 湾仔区| 海阳市| 城口县| 隆子县| 杂多县| 杭州市| 抚顺县| 开鲁县| 海兴县| 麦盖提县| 舟曲县| 东兰县| 冀州市| 定西市| 岳阳县| 溆浦县| 衡阳市|