`
阅读更多

总结一下与字节数组相关的IO操作。

关于 把十六进制的位串转化为byte数组,请参阅 http://hw1287789687.iteye.com/blog/1882644

 

(1)从InputStream 读取字节数组

方式一:

/***
	 * Has been tested
	 * 
	 * @param in
	 * @return
	 * @throws IOException
	 */
	public static byte[] readBytes3(InputStream in) throws IOException {
		BufferedInputStream bufin = new BufferedInputStream(in);
		int buffSize = BUFFSIZE_1024;
		ByteArrayOutputStream out = new ByteArrayOutputStream(buffSize);

		// System.out.println("Available bytes:" + in.available());

		byte[] temp = new byte[4096];
		int size = 0;
		while ((size = bufin.read(temp)) != -1) {
			out.write(temp, 0, size);
		}
		bufin.close();
		in.close();
		byte[] content = out.toByteArray();
		return content;
	}

 说明:先把inputstream的字节读到ByteArrayOutputStream中,读完之后再调用toByteArray() 转化为字节数组。

 

方式二:

/***
	 * Has been tested
	 * 
	 * @param in
	 * @return
	 * @throws IOException
	 */
	public static byte[] readBytes(InputStream in) throws IOException {
		byte[] temp = new byte[in.available()];
		byte[] result = new byte[0];
		int size = 0;
		while ((size = in.read(temp)) != -1) {
			byte[] readBytes = new byte[size];
			System.arraycopy(temp, 0, readBytes, 0, size);
			result = mergeArray(result, readBytes);
		}
		return result;
	}
/***
	 * 合并字节数组
	 * 
	 * @param a
	 * @return
	 */
	public static byte[] mergeArray(byte[]... a) {
		// 合并完之后数组的总长度
		int index = 0;
		int sum = 0;
		for (int i = 0; i < a.length; i++) {
			sum = sum + a[i].length;
		}
		byte[] result = new byte[sum];
		for (int i = 0; i < a.length; i++) {
			int lengthOne = a[i].length;
			if (lengthOne == 0) {
				continue;
			}
			// 拷贝数组
			System.arraycopy(a[i], 0, result, index, lengthOne);
			index = index + lengthOne;
		}
		return result;
	}

 

 

(2)把字节数组写入文件

/***
	 * write byte[] to file
	 * 
	 * @param bytes
	 * @param destFile
	 * @throws IOException
	 */
	public static void writeBytesToFile(byte[] bytes, File destFile)
			throws IOException {
		FileOutputStream out = new FileOutputStream(destFile);
		write2File(bytes, out);
	}
/***
	 * 
	 * @param bytes
	 * @param out
	 * @throws IOException
	 */
	public static void write2File(byte[] bytes, FileOutputStream out)
			throws IOException {
		out.write(bytes);
		out.close();
	}

 

 

(3)在已有字节数组基础上追加一个字节

/***
	 * append a byte.
	 * 
	 * @param a
	 * @param b
	 * @return
	 */
	public static byte[] appandByte(byte[] a, byte b) {
		int length = a.length;
		byte[] resultBytes = new byte[length + 1];
		System.arraycopy(a, 0, resultBytes, 0, length);
		resultBytes[length] = b;
		return resultBytes;
	}

 

(4)比较两个字节数组是否相同

/***
	 * Compare two byte arrays whether are the same.
	 * 
	 * @param a
	 * @param b
	 * @return
	 */
	public static boolean arrayIsEqual(byte[] a, byte[] b) {
		if(a==null&&b==null){
			return true;
		}
		
		if (a != null && b != null) {
			if (a.length != b.length) {
				return false;
			} else {
				for (int i = 0; i < a.length; i++) {
					if (a[i] != b[i]) {
						return false;
					}
				}
			}
		}else {//one is null, the other is not null
			return false;
		}
		return true;
	}

 

(5)查找指定字节findTarget在指定字节数组source中的位置

/***
	 * 
	 * @param source
	 * @param findTarget
	 *            :key word
	 * @param pos
	 *            :where start from
	 * @return index
	 */
	public static int findBytes(byte[] source, byte[] findTarget, int pos) {
		int i, j, k = 0;
		i = pos;
		j = 0;
		while (i < source.length && j < findTarget.length) {
			if (source[i] == findTarget[j]) {
				++i;
				++j;
				if (j == findTarget.length) {
					k = k + 1;// k++
					break;
					// j = 0;
				}
			} else {
				i = i - j + 1;
				j = 0;
			}
		}
		return k == 0 ? -1 : i - j;
	}

 

 

测试代码:

 @Test
    public void test_arrayIsEqual2(){
    	System.out.println("test_filterFrontBytes");
		byte[] a = new byte[] { 1, 2, 3, 4 };
		byte[] b = new byte[] { 1, 2, 3 };
		System.out.println( arrayIsEqual(a, b));
}
@Test
	public void test_appandByte(){
		byte[]bytes=new byte[]{1,2,3};
		byte[]resultBytes=appandByte(bytes, (byte)32);
		arrayIsEqual(resultBytes, new byte[]{1, 2, 3, 32});
	}

 

0
0
分享到:
评论

相关推荐

    在C#中将任意数值类型数据与字节数组相互转换的一个方法及源代码

    using System.IO; …… float f1 = 1.1F MemoryStream s = new MemoryStream(); BinaryWriter w=new BinaryWriter(s );

    C#中结构体和字节数组转换实现

    最近在使用结构体与字节数组转化来实现socket间数据传输。现在开始整理一下。对于Marshal可以查阅msdn,关于字节数组与结构体转代码如下: using System; using System.Collections.Generic; using System.Linq; ...

    java从输入流中获取数据并返回字节数组示例

    //从输入流中获取数据并以字节数组返回public class StreamTool { /** * 从输入流获取数据 * @param inputStream * @return * @throws Exception */ public static byte[] readInputStream(InputStream ...

    Java中的IO流(一)字节流的常用操作

    各种字节流的用法①节点流②处理流③流的使用一般步骤④流的关闭具体用法Ⅰ文件流Ⅱ字节数组流Ⅲ缓冲流Ⅳ转换流Ⅴ数据流Ⅵ对象流(序列化和反序列化)Ⅶ打印流(PrintStream)Ⅷ附加:随机访问流最后 前言 今天带来...

    java IO流学习笔记——(2)文件字符流&字节数组流

    java IO流学习笔记——(2)文件字符流&字节数组流 文件字符流FileReader&FileWriter FileReader :通过字符的方式读取文件,仅适合字符文件 FileWriter :通过字节的方式写出或追加数据到文件中,仅适合字符文件 部分...

    Java的IO流讲解代码: File 类、RandomAccessFile 类、字节流(文件字节流、缓冲字节流、基本数据类型

    File 类、RandomAccessFile 类、字节流(文件字节流、缓冲字节流、基本数据类型字节流、打印流、对象序列化流、字节数组流)、字符流(缓冲字符流、文件字符流、转换流、格式化输出流、字符数组流) 这份代码源码...

    c#泛型序列化对象为字节数组的示例

    序列化对象为字节数组 代码如下:using System.IO;using System.Runtime.Serialization.Formatters.Binary; protected byte[] Serialize(T t) { MemoryStream mStream = new MemoryStream(); BinaryFormatter ...

    day019-io笔记和代码.rar

    * 根据默认字符集将字节数组中从指定下标开始到指定长度结束的数据转换为字符串 * * 2.String(byte[] bytes, int offset, int length, String charsetName) * 根据指定字符集将字节数组...

    commons-io-2.CHM

    writeByteArrayToFile:将字节数组内容写到文件中。 writeLines:将容器中的元素的toString方法返回的内容依次写入文件中。 writeStringToFile:将字符串内容写到文件中。 二、IOUtils 打开IOUtils的api文档,我们...

    操作系统-IO设备和设备控制器.pptx

    数组选择通道是将数组选择通道传输速率高和字节多路通道能使各子通道(设备)分时并行操作的优点相结合而形成的一种新通道。数组多路通道是将数组选择通道传输速率高和字节多路通道能使各子通道(设备)分时并行操作...

    java高级特性 - io流.docx

    ByteArrayInputStream、ByteArrayOutputStream 用于字节数组操作;BufferedInputStream、BufferedOutputStream 用于缓冲操作等。 字符流(Character Streams): 字符流以字符为单位进行读写操作,适合于处理经过...

    Java面向对象程序设计第08章_Java-IO流.ppt

    * 字节流:处理单元为 1 个字节,操作字节和字节数组 * 字符流:处理单元为 2 个字节的 Unicode 字符,分别操作字符、字符数组或字符串 这四个类为抽象类,不能直接用来创建对象。 8.2 File 类 File 类用于表示...

    Java字节流与字符流的介绍.pdf

    Java 字节流与字符流的介绍 Java 中的流操作可以分为两种:字节流和字符流。字节流是指以 byte 为单位进行读写操作的流,而字符流是指以 char 为单位进行读写操作的流。 字节流的介绍 字节流的所有读操作都继承自...

    C#将图片和字节流互相转换并显示到页面上

    图片转换成字节流先要转换的IMage对象,转换之后返回字节流。字节流转换成图片,要转换的字节流,转换得到的Image对象,根据图片路径返回图片的字节流,感兴趣的朋友看下下面的代码。 C#将图片和字节流相互转换代码...

    hex-magic:用十六进制字符串和字节做魔术的Rust宏

    是一个宏,它在编译时将字符串文字( "7D2B" )转换为字节数组( [0x7D, 0x2B] )或匹配模式。 assert_eq!(hex!("01020304"), [1, 2, 3, 4]); parse_struct! parse_struct! 是一个宏,用于将Read器中的字节解析为...

    C# 读取 文件 方法

    //第一个参数是被传进来的字节数组,用以接受FileStream对象中的数据,第2个参数是字节数组中开始写入数据的位置,它通常是0,表示从数组的开端文件中向数组写数据,最后一个参数规定从文件读多少字符. }

    Java之IO流学习总结

    该对象并不是流体系中的一员,其封装了字节流,同时还封装了一个缓冲区(字符数组),通过内部的指针来操作字符数组中的数据。 该对象特点: 该对象只能操作文件,所以构造函数接收两种类型的参数:a.字符串文件...

    Java文件处理工具类--FileUtil

    * 从输入流读取数据为二进制字节数组. * @param streamIn * @return * @throws IOException */ public static byte[] readFileBinary(InputStream streamIn) throws IOException { BufferedInputStream...

    IO输入输出留

    //将一个文件看做是一个字节数组 //用下标值访问摸个位置的字节值 创建实例 ----------------------- 1 RandomAccessFile raf= new RandomAccessFile(文件,“r”) r 只读模式 1 RandomAccessFile raf= new ...

    IO体系.java

    |--ByteArrayInputStream/:字节数组输入流。操作的都是内存中的数组,所以不需要关闭。把数组封装到流中,可以提供更多的方法操作数组。 | |--SequenceInputStream/:序列流。将多个读取流合并成一个读取流,可以...

Global site tag (gtag.js) - Google Analytics