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

本文介绍了如何在Java中使用指定编码(如UTF-8)进行文件的读写操作,以避免出现乱码问题。提供了读取文件内容到List、将List写入文件以及根据字符串生成指定编码文件的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

可以指定编码如:utf-8来写入和读取文件。如果文件编码未知,可以通过该方法先得到文件的编码后再指定正确的编码来读取,否则会出现文件乱码问题。

如何识别文件编码请参考:java自动根据文件内容的编码来读取避免乱码

public class ReadWriteFileWithEncode { 

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

       File file = newFile("D:\\FACE_LIST\\TOSMIS_FACE_ALL_LIST.txt");//读取文件内容到List中
        List<String> ls =read(file.getPath(), "UTF-8");
        for (String line : ls) {
           String[] cols =StringUtils.splitPreserveAllTokens(line,Constants.SUF_PAD);
           System.out.println("解析数据:"+cols[0]);
        }

    }
    /*把数据写入到文件File中*/
    public static void write(String path, String content, Stringencoding) 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();
    }  
    /*从文件File中读取数据到字符串里*/
    public static List<String> read(String path,String encoding) throws IOException {  
        List<String> ls = newLinkedList<String>();
        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) {
            ls.add(line+"\n");
        }
        reader.close();
        return ls;

    }     

   /*根据组织好的字符串String生成,指定格式'UTF-8'文件*/

    public static void genFile(StringfileName, StringBuffer content) throws IOException {
        File file = new File(fileName);
        // 文件夹是否存在,不存在则创建
        String path =StringUtils.substringBeforeLast(fileName, "\\");
        File dir = new File(path);
        if (!dir.exists()) {
           org.apache.commons.io.FileUtils.forceMkdir(dir);
        }
        if (!file.exists()) {
            file.createNewFile();
        }
        org.apache.commons.io.FileUtils.writeStringToFile(file,content.toString(), "UTF-8");
        content = null;
    }

}

完整代码下载地址:http://www.zuidaima.com/share/1550463414258688.htm

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值