「java接收二进制数据」java中的二进制

博主:adminadmin 2022-11-22 21:49:09 66

本篇文章给大家谈谈java接收二进制数据,以及java中的二进制对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。

本文目录一览:

java中怎么输入二进制数据

Java中Scanner 是输入函数,首先建立一个输入函数,直接读取输入的二进制数据,然后通过Integer.valueOf转换成十进制即可。

Scanner input=new Scanner(System.in);

int length=input.nextInt();//输入二进制数据

int length10 = Integer.valueOf(length,10)//转换成十进制

java中用socket时怎么用2进制传输数据流?

对二进制的文件处理的时候,应该使用FileInputStream和FileOutputStream import java.io.*;

public class LinkFile

{

public static void main(String[] args) throws IOException

{

linkBinaryFile("Idea.jpg");

}

private static void linkBinaryFile(String fileName) throws IOException

{

File imageFile = new File(fileName);

if(!imageFile.exists()!imageFile.canRead())

{

System.out.println("can not read the image or the image file doesn't exists");

System.exit(1);

}

long length = imageFile.length();

int ch = 0;

System.out.println(length);

byte[] buffer = new byte[(int)length/7];

InputStream image = new FileInputStream(imageFile);

File file = new File("hello.jpg");

if(!file.exists())

{

file.createNewFile();

}

FileOutputStream newFile = new FileOutputStream(file,true);

boolean go = true;

while(go)

{

System.out.println("please select how to read the file:\n"+

"1: read()\n2:read(byte[] buffer)\n3:read(byte[] buffer,int off,int len)\n");

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

String line = br.readLine();

if(line.equals("1"))

{

while((ch = image.read())!=-1)

{

System.out.print(ch);

newFile.write(ch);

}

}

else if(line.equals("2"))

{

while((ch = image.read(buffer))!=-1)

{

System.out.println(ch);

newFile.write(buffer);

}

}

else if(line.equals("3"))

{

while((ch = image.read(buffer,10,500))!=-1)

{

System.out.println(ch);

newFile.write(buffer,10,500);

TCP/IP协议 怎么用JAVA发送和接收二进制数据 要具体实例

1.TCP/IP协议要求信息必须在块(chunk)中发送和接收,而块的长度必须是8位的倍数,因此,我们可以认为TCP/IP协议中传输的信息是字节序列。如何发送和解析信息需要一定的应用程序协议。

2.信息编码:

首先是Java里对基本整型的处理,发送时,要注意:1)每种数据类型的字节个数;2)这些字节的发送顺序是怎样的?(little-endian还是

big-endian);3)所传输的数值是有符号的(signed)还是无符号的(unsigned)。具体编码时采用位操作(移位和屏蔽)就可以了。

具体在Java里,可以采用DataOutputStream类和ByteArrayOutputStream来实现。恢复时可以采用

DataInputStream类和ByteArrayInputStream类。

其次,字符串和文本,在一组符号与一组整数之间的映射称为编码字符集(coded character

set)。发送者与接收者必须在符号与整数的映射方式上达成共识,才能使用文本信息进行通信,最简单的方法就是定义一个标准字符集。具体编码时采用

String的getBytes()方法。

最后,位操作。如果设置一个特定的设为1,先设置好掩码(mask),之后用或操作;要清空特定一位,用与操作。

3.成帧与解析

成帧(framing)技术解决了接收端如何定位消息的首位位置的问题。

如果接收者试图从套接字中读取比消息本身更多的字节,将可能发生以下两种情况之一:如果信道中没有其他消息,接收者将阻塞等待,同时无法处理接收

到的消息;如果发送者也在等待接收端的响应消息,则会形成死锁(dealock);另一方面,如果信道中还有其他消息,则接收者会将后面消息的一部分甚至

全部读到第一条消息中去,这将产生一些协议错误。因此,在使用TCP套接字时,成帧就是一个非常重要的考虑因素。

有两个技术:

1.基于定界符(Delimiter-based):消息的结束由一个唯一的标记(unique

marker)指出,即发送者在传输完数据后显式添加的一个特殊字节序列。这个特殊标记不能在传输的数据中出现。幸运的是,填充(stuffing)技术

能够对消息中出现的定界符进行修改,从而使接收者不将其识别为定界符。在接收者扫描定界符时,还能识别出修改过的数据,并在输出消息中对其进行还原,从而

使其与原始消息一致。

2.显式长度(Explicit length):在变长字段或消息前附加一个固定大小的字段,用来指示该字段或消息中包含了多少字节。这种方法要确定消息长度的上限,以确定保存这个长度需要的字节数。

接口:

Java代码 import java.io.IOException; import java.io.OutputStream; public interface Framer { void frameMsg(byte [] message,OutputStream out) throws IOException; byte [] nextMsg() throws IOException; }

定界符的方式:

Java代码 import java.io.ByteArrayOutputStream; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class DelimFramer implements Framer { private InputStream in;//data source; private static final byte DELIMTER=(byte)'\n';//message delimiter public DelimFramer(InputStream in){ this.in=in; } @Override public void frameMsg(byte[] message, OutputStream out) throws IOException { //ensure that the message dose not contain the delimiter for(byte b:message){ if(b==DELIMTER) throw new IOException("Message contains delimiter"); } out.write(message); out.write(DELIMTER); out.flush(); } @Override public byte[] nextMsg() throws IOException { ByteArrayOutputStream messageBuffer=new ByteArrayOutputStream(); int nextByte; while((nextByte=in.read())!=DELIMTER){ if(nextByte==-1){//end of stream? if(messageBuffer.size()==0){ return null; }else{ throw new EOFException("Non-empty message without delimiter"); } } messageBuffer.write(nextByte); } return messageBuffer.toByteArray(); } }

显式长度方法:

Java代码 import java.io.DataInputStream; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class LengthFramer implements Framer { public static final int MAXMESSAGELENGTH=65535; public static final int BYTEMASK=0xff; public static final int SHOTMASK=0xffff; public static final int BYTESHIFT=8; private DataInputStream in;// wrapper for data I/O public LengthFramer(InputStream in) throws IOException{ this.in=new DataInputStream(in); } @Override public void frameMsg(byte[] message, OutputStream out) throws IOException { if(message.lengthMAXMESSAGELENGTH){ throw new IOException("message too long"); } //write length prefix out.write((message.lengthBYTEMASK)BYTEMASK); out.write(message.lengthBYTEMASK); //write message out.write(message); out.flush(); } @Override public byte[] nextMsg() throws IOException { int length; try{ length=in.readUnsignedShort(); }catch(EOFException e){ //no (or 1 byte) message; return null; } //0=length=65535; byte [] msg=new byte[length]; in.readFully(msg);//if exception,it's a framing error; return msg; } }

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读取二进制文件中的数据的问题

二进制读取文件的形式中如果用的是read读取,那么此时就会出现乱码问题(中文是两个字节,read只能读取一个),所以都是通过readline方法来进行整行的内容读取来进行问题解决。

可以通过BufferedReader 流的形式进行流缓存,之后通过readLine方法获取到缓存的内容。

BufferedReader bre = null;

try {

String file = "D:/test/test.txt";

bre = new BufferedReader(new FileReader(file));//此时获取到的bre就是整个文件的缓存流

while ((str = bre.readLine())!= null) // 判断最后一行不存在,为空结束循环

{

System.out.println(str);//原样输出读到的内容

};

备注: 流用完之后必须close掉,如上面的就应该是:bre.close(),否则bre流会一直存在,直到程序运行结束。

关于java接收二进制数据和java中的二进制的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。

The End

发布于:2022-11-22,除非注明,否则均为首码项目网原创文章,转载请注明出处。