「java解析二进制文件」java读取二进制文件

博主:adminadmin 2023-01-12 20:21:09 782

今天给各位分享java解析二进制文件的知识,其中也会对java读取二进制文件进行解释,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!

本文目录一览:

java实现解析二进制文件

/**

*

*/

package com.igen.case10;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.net.URISyntaxException;

/**

*

* @ClassName Case10

* @Description TODO

*

* @author wjggwm

* @data 2017年2月7日 上午11:46:25

*/

public class Case10 {

static final String fileName = "/test.png";

static final String filePath = "D:/files/case10";

static final String sourceFileName = "binary";

public static void main(String[] args) {

try {

readFile(Case10.class.getResource(sourceFileName).toURI().getPath());

} catch (URISyntaxException e) {

e.printStackTrace();

}

}

/**

*

* @Description 解析二进制文件

* @param sourceFileName

*

* @author wjggwm

* @data 2017年2月7日 上午11:47:12

*/

public static void readFile(String sourceFileName) {

InputStream in = null;

try {

in = new FileInputStream(sourceFileName);

// 读取字符串数据长度字节

byte[] txtLenByte = new byte[2];

in.read(txtLenByte);

int txtlen = byte2ToUnsignedShort(txtLenByte, 0);

// 读取字符串字节

byte[] txtByte = new byte[txtlen];

in.read(txtByte);

//字符串为UTF-8编码

String txt = new String(txtByte, "UTF-8");

// 输出字符串

System.out.println(txt);

// 读取图片数据长度

byte[] imgLenByte = new byte[4];

in.read(imgLenByte);

int imgLen = byte4ToInt(imgLenByte, 0);

// 读取图片数据

byte[] img = new byte[imgLen];

in.read(img);

// 生成图片文件

saveToImgByBytes(filePath, fileName, img);

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} finally {

if (in != null) {

try {

in.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

/**

*

* @Description 将字节写入文件

* @param imgName

* @param imgByte

*

* @author wjggwm

* @data 2017年2月7日 上午11:07:45

*/

public static void saveToImgByBytes(String filePath, String imgName, byte[] imgByte) {

try {

File dic = new File(filePath);

if (!dic.exists()) {

dic.mkdirs();

}

File image = new File(filePath + imgName);

if (!image.exists()) {

image.createNewFile();

}

FileOutputStream fos = new FileOutputStream(image);

fos.write(imgByte);

fos.flush();

fos.close();

} catch (Exception e) {

e.printStackTrace();

}

}

/**

*

* @Description byte数组转换为无符号short整数

* @param bytes

* @param off

* @return

*

* @author wjggwm

* @data 2017年2月7日 上午11:05:58

*/

public static int byte2ToUnsignedShort(byte[] bytes, int off) {

// 注意高位在后面,即大小端问题

int low = bytes[off];

int high = bytes[off + 1];

return (high 8 0xFF00) | (low 0xFF);

}

/**

*

* @Description byte数组转换为int整数

* @param bytes

* @param off

* @return

*

* @author wjggwm

* @data 2017年2月7日 上午11:07:23

*/

public static int byte4ToInt(byte[] bytes, int off) {

// 注意高位在后面,即大小端问题

int b3 = bytes[off] 0xFF;

int b2 = bytes[off + 1] 0xFF;

int b1 = bytes[off + 2] 0xFF;

int b0 = bytes[off + 3] 0xFF;

return (b0 24) | (b1 16) | (b2 8) | b3;

}

}

如何用Java或C语言解析二进制文件为文本文件?

在学习C语言fopen()函数后,知道它的第二个参数是标志字符串。如果字符串中出现'b',则表明是以打开二进制(binary)文件,否则是打开文本文件。

那么什么是文本文件,什么是二进制文件呢?

从文件编码的方式来看,文件可分为ASCII码文件和二进制码文件两种。

ASCII文件也称为文本文件,这种文件在磁盘中存放时每个字符对应一个字节,用于存放对应的ASCII码。例如,数5678的存储形式为:

ASC码: 00110101 00110110 00110111 00111000

↓ ↓↓  ↓

十进制码: 5 678

共占用4个字节。ASCII码文件可在屏幕上按字符显示, 例如源程序文件就是ASCII文件,用DOS命令TYPE可显示文件的内容。 由于是按字符显示,因此能读懂文件内容。

二进制文件是按二进制的编码方式来存放文件的。例如,数5678的存储形式为:00010110 00101110只占二个字节。二进制文件虽然也可在屏幕上显示,但其内容无法读懂。C系统在处理这些文件时,并不区分类型,都看成是字符流,按字节进行处理。输入输出字符流的开始和结束只由程序控制而不受物理符号(如回车符)的控制。因此也把这种文件称作“流式文件”。

文本文件与二进制文件的区别在系统存储上它们实际上并没有什么区别,都是以二进制的方式存储于硬盘上。之所以分二进制文件和文本文件,主要是逻辑上的区分,文本文件更人为可读而已。站在编程的角度看,文本文件是基于字符编码过后的,比如常见的就有ascii编码,gbk编码,unicode编码等,文本工具直接打开人为可读。而二进制文件是基于值的编码,这个值到底是什么,完全可自定义,所以可以说二进制文件是一种特殊编码的文件。如果用java编程,可能就根本没遇到过以二进制打开和文本文件打开这两种方式。java里面有字符流和字节流,字符流是对字节流的封装,有编码解码,而字节流操作的则是byte数组,所以更容易理解。python的文件读写方式则更贴近C。因为python和java他们底层都是C,所以很有必要弄清C的读写文件方式。

在Windows和DOS系统中,狭义的文本文件是指扩展名为txt的文件。实际上,那些没有规定格式的,由可理解的的ASCII以及其他编码文字组成的文件都是文本文件,如C源程序文件,HTML超文本,XML。除此之外的其他文件都是二进制文件,如Word文件DOC,图象格式文件JPG。

实际上,fopen()的 b 标志不但可以打开二进制文件,还可以打开文本文件,同样,不带 b 标志也可以打开文本文件。

既然这样,为什么还要区分两种打开方式呢?

因为这两种方式在读写文件时的操作是不一样的。

二进制方式很简单,读文件时,会原封不动的读出文件的全部内容,写的时候,也是把内存缓冲区的内容原封不动的写到文件中。

而文本方式就不一样了,在写文件时,会将换行符号CRLF(0x0D 0x0A)全部转换成单个的0x0A,并且当遇到结束符CTRLZ(0x1A)时,就认为文件已经结束。相应的,写文件时,会将所有的0x0A换成0x0D0x0A。

所以,若使用文本方式打开二进制文件时,就很容易出现文件读不完整,或内容不对的错误。即使是用文本方式打开文本文件,也要谨慎使用,比如复制文件,就不应该使用文本方式。

要特别注意的是,上面这样的说法仅适用于DOS和Windows系统。在Unix和其他一些系统中,没有文本方式和二进制方式的区分,使不使用'b'标志都是一样的。这是由于不同操作系统对文本文件换行符的定义,和C语言中换行符的定义有所不同而造成的。

如上文已提到,DOS和Windows系统使用CRLF(0x0D 0x0A)即\r\n双字节作为文本文件换行符,而Unix文本文件的换行符只有一个字节LF(0x0A)为。在C语言中,也是以LF即'\n'为换行符。

由于DOS/Windows定义的换行符和C语言的不一致,C语言的标准输入输出函数适行读写文本文件时,就适行了CRLF-LF的转换。而Unix的定义和C语言的是一样的,就不必转换了。

那么,为什么会有定义不一致的情况呢,这纯属历史原因。当初C是在Unix上发展的,对换行的定义自然就一样了。其后C被引入到DOS系统,为了使原有的C程序能不加修改的读写DOS的文本文件,所以就在文件读写上做了修改。随着DOS/Windows成为主流平台,这个当初为了兼容而做的修改给众多的C语言开发者添了这样一个小小的麻烦。

所以,二进制和文本模式的区别就在于对于换行符和一些非可见字符上面的转化,所以安全起见,是使用二进制读取会比较安全一些。

java 如何解析WebSocket传输的二进制数据

JS操作websocket接收的二进制,安全性能有保障,已经过一年实践考验:

[javascript] view plain copy

ws.onmessage = function(evt) {

if(typeof(evt.data)=="string"){

textHandler(JSON.parse(evt.data));

}else{

var reader = new FileReader();

reader.onload = function(evt){

if(evt.target.readyState == FileReader.DONE){

var data = new Uint8Array(evt.target.result);

handler(data);

}

}

reader.readAsArrayBuffer(evt.data);

}

};

[html] view plain copy

function handler(data){

switch(data[0]){

case 1:

getCard(data[1]);

break;

...

JS操作websocket接收的图片,今天刚写的,也是用filereader实现。

[html] view plain copy

ws.onmessage = function(evt) {

if(typeof(evt.data)=="string"){

//textHandler(JSON.parse(evt.data));

}else{

var reader = new FileReader();

reader.onload = function(evt){

if(evt.target.readyState == FileReader.DONE){

var url = evt.target.result;

alert(url);

var img = document.getElementById("imgDiv");

img.innerHTML = "img src = "+url+" /";

}

}

reader.readAsDataURL(evt.data);

}

};

java读取二进制文件

思路:按照字节读取文件到缓冲,然后对文件内容进行处理。

代码如下:

public static void readFile() throws IOException{

    RandomAccessFile f = new RandomAccessFile("test.txt", "r");

    byte[] b = new byte[(int)f.length()];

    //将文件按照字节方式读入到字节缓存中

    f.read(b);

    //将字节转换为utf-8 格式的字符串

    String input = new String(b, "utf-8");

    //可以匹配到所有的数字

    Pattern pattern = Pattern.compile("\\d+(\\.\\d+)?");

    Matcher match = pattern.matcher(input);

    while(match.find()) {

        //match.group(0)即为你想获取的数据

        System.out.println(match.group(0));

    }

    f.close();

}

JAVA中读取文件(二进制,字符)内容的几种方

JAVA中读取文件内容的方法有很多,比如按字节读取文件内容,按字符读取文件内容,按行读取文件内容,随机读取文件内容等方法,本文就以上方法的具体实现给出代码,需要的可以直接复制使用

public class ReadFromFile {

/**

* 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。

*/

public static void readFileByBytes(String fileName) {

File file = new File(fileName);

InputStream in = null;

try {

System.out.println("以字节为单位读取文件内容,一次读一个字节:");

// 一次读一个字节

in = new FileInputStream(file);

int tempbyte;

while ((tempbyte = in.read()) != -1) {

System.out.write(tempbyte);

}

in.close();

} catch (IOException e) {

e.printStackTrace();

return;

}

try {

System.out.println("以字节为单位读取文件内容,一次读多个字节:");

// 一次读多个字节

byte[] tempbytes = new byte[100];

int byteread = 0;

in = new FileInputStream(fileName);

ReadFromFile.showAvailableBytes(in);

// 读入多个字节到字节数组中,byteread为一次读入的字节数

while ((byteread = in.read(tempbytes)) != -1) {

System.out.write(tempbytes, 0, byteread);

}

} catch (Exception e1) {

e1.printStackTrace();

} finally {

if (in != null) {

try {

in.close();

} catch (IOException e1) {

}

}

}

}

/**

* 以字符为单位读取文件,常用于读文本,数字等类型的文件

*/

public static void readFileByChars(String fileName) {

File file = new File(fileName);

Reader reader = null;

try {

System.out.println("以字符为单位读取文件内容,一次读一个字节:");

// 一次读一个字符

reader = new InputStreamReader(new FileInputStream(file));

int tempchar;

while ((tempchar = reader.read()) != -1) {

// 对于windows下,\r\n这两个字符在一起时,表示一个换行。

// 但如果这两个字符分开显示时,会换两次行。

// 因此,屏蔽掉\r,或者屏蔽\n。否则,将会多出很多空行。

if (((char) tempchar) != '\r') {

System.out.print((char) tempchar);

}

}

reader.close();

} catch (Exception e) {

e.printStackTrace();

}

try {

System.out.println("以字符为单位读取文件内容,一次读多个字节:");

// 一次读多个字符

char[] tempchars = new char[30];

int charread = 0;

reader = new InputStreamReader(new FileInputStream(fileName));

// 读入多个字符到字符数组中,charread为一次读取字符数

while ((charread = reader.read(tempchars)) != -1) {

// 同样屏蔽掉\r不显示

if ((charread == tempchars.length)

(tempchars[tempchars.length - 1] != '\r')) {

System.out.print(tempchars);

} else {

for (int i = 0; i charread; i++) {

if (tempchars[i] == '\r') {

continue;

} else {

System.out.print(tempchars[i]);

}

}

}

}

} catch (Exception e1) {

e1.printStackTrace();

} finally {

if (reader != null) {

try {

reader.close();

} catch (IOException e1) {

}

}

}

}

/**

* 以行为单位读取文件,常用于读面向行的格式化文件

*/

public static void readFileByLines(String fileName) {

File file = new File(fileName);

BufferedReader reader = null;

try {

System.out.println("以行为单位读取文件内容,一次读一整行:");

reader = new BufferedReader(new FileReader(file));

String tempString = null;

int line = 1;

// 一次读入一行,直到读入null为文件结束

while ((tempString = reader.readLine()) != null) {

// 显示行号

System.out.println("line " + line + ": " + tempString);

line++;

}

reader.close();

} catch (IOException e) {

e.printStackTrace();

} finally {

if (reader != null) {

try {

reader.close();

} catch (IOException e1) {

}

}

}

}

/**

* 随机读取文件内容

*/

public static void readFileByRandomAccess(String fileName) {

RandomAccessFile randomFile = null;

try {

System.out.println("随机读取一段文件内容:");

// 打开一个随机访问文件流,按只读方式

randomFile = new RandomAccessFile(fileName, "r");

// 文件长度,字节数

long fileLength = randomFile.length();

// 读文件的起始位置

int beginIndex = (fileLength 4) ? 4 : 0;

// 将读文件的开始位置移到beginIndex位置。

randomFile.seek(beginIndex);

byte[] bytes = new byte[10];

int byteread = 0;

// 一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。

// 将一次读取的字节数赋给byteread

while ((byteread = randomFile.read(bytes)) != -1) {

System.out.write(bytes, 0, byteread);

}

} catch (IOException e) {

e.printStackTrace();

} finally {

if (randomFile != null) {

try {

randomFile.close();

} catch (IOException e1) {

}

}

}

}

/**

* 显示输入流中还剩的字节数

*/

private static void showAvailableBytes(InputStream in) {

try {

System.out.println("当前字节输入流中的字节数为:" + in.available());

} catch (IOException e) {

e.printStackTrace();

}

}

public static void main(String[] args) {

String fileName = "C:/temp/newTemp.txt";

ReadFromFile.readFileByBytes(fileName);

ReadFromFile.readFileByChars(fileName);

ReadFromFile.readFileByLines(fileName);

ReadFromFile.readFileByRandomAccess(fileName);

}

}

Java怎么解析用C写入的.bin类型二进制文件

Java怎么解析用C写入的.bin类型二进制文件

\\假设文件的地址为a.txt

FileInputStream in=new FileInputStream(new File("a.txt"));

byte[] buffer=new byte[4096];

int offset=0;

while((offset=in.read(buffer)-1){

//这已经把文件读入到buffer中了,范围为0到offset,你可以做任何处理了

}

in.close();

java解析二进制文件的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于java读取二进制文件、java解析二进制文件的信息别忘了在本站进行查找喔。