import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;import java.io.InputStream;import java.io.Reader;public class ReaderDemo { /** * 使用字符流读取文本文件 */ public static void stringReader(){ File f = new File("E:\\测试用例.txt"); try { //构造一个字符输入流对象 Reader ri = new FileReader(f); char[] cs = new char[20]; int len = -1; StringBuffer sb = new StringBuffer(); while ((len = ri.read(cs))!=-1){ sb.append(new String(cs,0,len)); } //关闭流 ri.close(); System.out.println(sb); } catch (FileNotFoundException e) { e.printStackTrace(); }catch (IOException e) { e.printStackTrace(); } } /** * 使用字节流读取文本文件 * @param args */ public static void byteReader(){ File f = new File("E:\\测试用例.txt"); try { InputStream is = new FileInputStream(f); byte[] bytes = new byte[1024]; int len = -1; StringBuffer sb = new StringBuffer(); while ((len = is.read(bytes))!=-1){ sb.append(new String(bytes,0,len)); } is.close(); System.out.println(sb); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { //byteReader(); stringReader(); }}
1 回答
已采纳
幕附
TA贡献78条经验 获得超18个赞
记得采纳欧
1、你检查一下你文件的保存格式是UTF8吗? 2、你看看String(byte[] bytes,
int offset,
int length, Charset charset)你理解这个构造函数吗?new String(bytes,0,len,“utf-8”)
添加回答
举报
0/150
提交
取消