java中inputstream的使用

java中的inputstream是一个面向字节的流抽象类,其依据详细应用派生出各种详细的类。

比方FileInputStream就是继承于InputStream,专门用来读取文件流的对象,其详细继承结构如图



我们发现。是从抽象类InputStream继承而来的。


我们继续看样例,实现从txt文件里。读取字符。当中test.txt已经提前新建好。放到project文件夹下了。

package com.itbuluoge.test;

import java.io.FileInputStream;

public class ByteInputFile {

	public static String read() throws Exception
	{
		FileInputStream fit=new FileInputStream("test.txt");	
		int c;
		String sb="";
		while((c=fit.read())!=-1)
		{
			sb+=(char)c;
		}
		return sb;
	}
	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		System.out.println(read());
	}

}


输出结果




这里要注意一点,InputStream是面向字节的流。因此每次操作都是针对于一个字节,因此就无法对中文进行处理,读出写入都会出现乱码。继承而来的FileInputStream是一样的。因此我们这里測试。仅仅是用了英文字符

原文地址:https://www.cnblogs.com/yangykaifa/p/7137715.html