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

你可能感兴趣的文章
PrintStream概述
查看>>
Prismix:Prisma 架构混合器,为复杂项目而生
查看>>
pritunl服务安装及配置
查看>>
Private Destructor
查看>>
private和protected能同时修饰成员变量吗_天天用注解你了解注解是怎么实现的吗?...
查看>>
privoxy Invalid header received from client.
查看>>
Privoxy代码下载
查看>>
Probabilistic-Programming-and-Bayesian-Methods-for-Hackers
查看>>
pytorch中的求和函数sum(axis=x)解释
查看>>
Problem F: 质心算法
查看>>
Problem N HDU 2612 Find a way (两次BFS求最值)
查看>>
Process /usr/libexec/gdu-notification-daemon was killed by signal 6 (SIGABRT)
查看>>
process.env.VUE_APP_BASE_API 获取不到
查看>>
Process.run() 和 Process.start() 之间的区别
查看>>
Processes
查看>>
Processing通过编程实现艺术设计_实现艺术和现实的交互---数据设计分析002
查看>>
ProcessOnLoading
查看>>
SpringBoot中集成screw(螺丝钉)实现数据库表结构文档生成
查看>>
PROFINET 模拟器使用教程
查看>>
Program type already present: android.support.v4.widget.EdgeEffectCompat
查看>>