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));
}
}