java 使用IO流读取指定文件中的内容

来源:互联网 发布:java开发环境是什么 编辑:程序博客网 时间:2024/05/21 18:26

一、使用字节流读取

我们先使用字节流一个一个读取

package com.uwo9.test01;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;public class Test08 {public static void main(String[] args) {// 1.定义目标文件File srcFile = new File("E:/Temp/Test1.txt");// 2.创建一个流,指向目标文件InputStream is = null;try {is = new FileInputStream(srcFile);// 3.循环往外流int content = is.read();// 4.循环打印while (content != -1) {System.out.print((char) content);content = is.read();}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {// 关闭io流try {is.close();} catch (IOException e) {e.printStackTrace();}}}}
我们会发现中文无法识别,汉字占两个字符。

解决方法:按字节数组读取


package com.uwo9.test01;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;public class Test08 {public static void main(String[] args) {// 1.定义目标文件File srcFile = new File("E:/Temp/Test1.txt");// 2.创建一个流,指向目标文件InputStream is = null;try {is = new FileInputStream(srcFile);//3.创建一个用来存储读取数据的缓冲数组byte[]array = new byte[128];//4.循环往外流(count为每次读取数组中的有效字节总数)int count = is.read(array);// 5.循环打印while (count != -1) {// 将byte[] -》 String// 将byte数组读取到的有效字节转换成字符串String string = new String(array, 0, count);System.out.print(string);count = is.read(array);}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {// 关闭io流try {is.close();} catch (IOException e) {e.printStackTrace();}}}}

可以看到,中文成功读取。但按照字节数组读取,还是有可能出现部分中文乱码问题,我们可以用字符流


二、使用字符流读取


package com.uwo9.test01;import java.io.File;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;import java.io.Reader;public class Test08 {public static void main(String[] args) {// 1.创建文件对象File fromFile = new File("E:/Temp/Test1.txt");// 2.创建字符输入流Reader reader = null;try {reader = new FileReader(fromFile);// 3.循环读取(打印)int content = reader.read();while (content != -1) {System.out.print((char) content);content = reader.read();}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally {// 4.关闭流try {reader.close();} catch (IOException e) {e.printStackTrace();}}}}


补:

字节流是 8 位通用字节流,字符流是 16 位 Unicode 字符流

获得当前开发环境的字符编码方式

System.out.println(System.getProperty("file.encoding"));