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

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

java中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());
	}

}


输出结果

java中inputstream的使用



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

相关文章:

  • 2021-09-29
  • 2021-08-14
  • 2022-12-23
  • 2022-12-23
  • 2022-01-14
  • 2022-12-23
  • 2021-09-14
  • 2021-05-19
猜你喜欢
  • 2022-12-23
  • 2021-12-15
  • 2022-12-23
  • 2021-05-23
  • 2021-07-17
  • 2022-12-23
相关资源
相似解决方案