手机
当前位置:查字典教程网 >编程开发 >Java >java按指定编码写入和读取文件内容的类分享
java按指定编码写入和读取文件内容的类分享
摘要:可以指定编码如:utf-8来写入和读取文件。如果文件编码未知,可以通过该方法先得到文件的编码后再指定正确的编码来读取,否则会出现文件乱码问题...

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

}

}

【java按指定编码写入和读取文件内容的类分享】相关文章:

Java如何读取XML文件 具体实现

java 实现文件复制和格式更改的实例

java中Scanner类的简单用法分享

java读取文件显示进度条的实现方法

java读取大文件简单实例

java自定义注解接口实现方案

将内容写到txt文档里面并读取及删除的方法

java实现sunday算法示例分享

java通过url读取文件内容示例

javamail 发送邮件的实例代码分享

精品推荐
分类导航