博客
关于我
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/

你可能感兴趣的文章
notepad如何自动对齐_notepad++怎么自动排版
查看>>
Notes on Paul Irish's "Things I learned from the jQuery source" casts
查看>>
Notification 使用详解(很全
查看>>
NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
查看>>
NotImplementedError: Could not run torchvision::nms
查看>>
nova基于ubs机制扩展scheduler-filter
查看>>
Now trying to drop the old temporary tablespace, the session hangs.
查看>>
nowcoder—Beauty of Trees
查看>>
np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
查看>>
np.power的使用
查看>>
NPM 2FA双重认证的设置方法
查看>>
npm build报错Cannot find module ‘webpack/lib/rules/BasicEffectRulePlugin‘解决方法
查看>>
npm build报错Cannot find module ‘webpack‘解决方法
查看>>
npm ERR! ERESOLVE could not resolve报错
查看>>
npm ERR! fatal: unable to connect to github.com:
查看>>
npm ERR! Unexpected end of JSON input while parsing near '...on":"0.10.3","direc to'
查看>>
npm ERR! Unexpected end of JSON input while parsing near ‘...“:“^1.2.0“,“vue-html-‘ npm ERR! A comp
查看>>
npm error Missing script: “server“npm errornpm error Did you mean this?npm error npm run serve
查看>>
npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
查看>>
npm install CERT_HAS_EXPIRED解决方法
查看>>