博客
关于我
Java文件字符输入流FileReader读取txt文件乱码问题
阅读量:327 次
发布时间:2019-03-04

本文共 1067 字,大约阅读时间需要 3 分钟。

Java读取文件内容时需要注意编码格式

在实际开发中,当我们需要读取文件内容时,尤其是处理文本文件,可能会遇到编码格式相关的问题。Java中的字符流处理的最基本单元是Unicode码元(大小2字节),所以在读取文件时,我们需要注意文件的编码格式。

在代码示例中,使用了FileReader来读取文件,但未设置编码格式。FileReader默认会使用平台的默认编码格式,这可能会导致读取文件时出现问题。如果文件编码格式与默认编码不符,可能会导致无法正确读取内容,甚至出现“未找到指定路径的文件”错误。

正确的做法是在读取文件时指定编码格式。对于大多数文本文件,UTF-8是一个常用的编码格式。我们可以在创建FileReader对象时,传入指定的编码格式字符集。

文件读取示例代码如下:

public class FileInAndOut {    public static void main(String[] args) {        File file = new File("E:/大三下学期/Android/作业要求/java知识巩固/work5.txt");        if (!file.exists()) {            System.out.println("对不起,不包含指定路径的文件");            return;        }        try {            FileReader fr = new FileReader(file, "UTF-8");            char[] data = new char[51];            int length = 0;            while ((length = fr.read(data)) > 0) {                String str = new String(data, 0, length);                System.out.println(str);            }            fr.close();        } catch (Exception e) {            e.printStackTrace();        }    }}

运行示例代码,假设文件路径正确且文件存在,程序会输出文件内容。

在实际开发中,记得始终使用UTF-8编码格式,这样可以确保文件内容能够被正确读取和显示。

转载地址:http://cooq.baihongyu.com/

你可能感兴趣的文章
npm报错fatal: Could not read from remote repository
查看>>
npm报错File to import not found or unreadable: @/assets/styles/global.scss.
查看>>
npm报错TypeError: this.getOptions is not a function
查看>>
npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
查看>>
npm淘宝镜像过期npm ERR! request to https://registry.npm.taobao.org/vuex failed, reason: certificate has ex
查看>>
npm版本过高问题
查看>>
npm的“--force“和“--legacy-peer-deps“参数
查看>>
npm的安装和更新---npm工作笔记002
查看>>
npm的常用操作---npm工作笔记003
查看>>
npm的常用配置项---npm工作笔记004
查看>>
npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
查看>>
npm编译报错You may need an additional loader to handle the result of these loaders
查看>>
npm设置淘宝镜像、升级等
查看>>
npm设置源地址,npm官方地址
查看>>
npm设置镜像如淘宝:http://npm.taobao.org/
查看>>
npm配置安装最新淘宝镜像,旧镜像会errror
查看>>
NPM酷库052:sax,按流解析XML
查看>>
npm错误 gyp错误 vs版本不对 msvs_version不兼容
查看>>
npm错误Error: Cannot find module ‘postcss-loader‘
查看>>
npm,yarn,cnpm 的区别
查看>>