码迷,mamicode.com
首页 > 编程语言 > 详细

java中inputstream的使用

时间:2014-10-15 19:22:41      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:blog   http   io   使用   ar   java   文件   2014   on   

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

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

bubuko.com,布布扣


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


我们继续看例子,实现从txt文件中,读取字符。其中test.txt已经提前新建好,放到工程目录下了。

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

}


输出结果

bubuko.com,布布扣



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

java中inputstream的使用

标签:blog   http   io   使用   ar   java   文件   2014   on   

原文地址:http://blog.csdn.net/itbuluoge/article/details/40113327

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!