FileInputStream读取一个或多个字符

版权声明:最终解释权归属Hern所有,恒! https://blog.csdn.net/qq_36761831/article/details/86262593

一次读取一个字符

利用read()方法进行读取,速度慢

               //加载一个文件,使用绝对路径定位文件
		
		String path = this.getServletContext().getRealPath("a.txt");
		System.out.println(path);
		
		//加载文件,二进制流字节码
		FileInputStream in = new FileInputStream(path);
		System.out.println(in);
		
		//获取字节码,一次读取一个字符
		while(true) {
			if(in.read() == -1) {//判断是否读取完毕
				break;
			}
			System.out.println(in.read());
		}
		
		//关闭文件
		in.close();

一次读取多个字符

利用byte[ ] 数组进行读取。

              //加载一个文件,使用绝对路径定位文件
		
		String path = this.getServletContext().getRealPath("a.txt");
		System.out.println(path);
		
		//加载文件,二进制流字节码
		FileInputStream in = new FileInputStream(path);
		System.out.println(in);
		
		byte[] buffer = new byte[1024];//一次读取多少字节
		int length = 0;//当前读取字符的长度,若一个都没有读取则返回-1
		
		while( (length = in.read(buffer)) != -1) {
			System.out.println(Arrays.toString(buffer));//输出每个字符对应的ASCII字节码
			System.out.println(new String(buffer,0,1024));//将字节码转换成对应的字符串
		}
		
		//关闭文件
		in.close();

简单在浏览器中显示一张图片

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		//获取文件路径
		String path = this.getServletContext().getRealPath("hern.png");
		
		//加载图片
		FileInputStream in = new FileInputStream(path);
		
		//获取一个输出流
		ServletOutputStream out = response.getOutputStream();
		
		byte[] buffer = new byte[1024];
		Integer length = 0;
		while( (length = in.read(buffer)) != -1) {
			System.out.println(length);
			System.out.println(Arrays.toString(buffer));
			out.write(buffer, 0, length);
		}
		
	}

猜你喜欢

转载自blog.csdn.net/qq_36761831/article/details/86262593