① 紧急求助!!!java语言下如何将二进制数字写入文件然后读出来
/** * 二进制读写文件 */ import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; public class MainClass { /** * java.io包中的OutputStream及其子类专门用于写二进制数据。 * FileOutputStream是其子类,可用于将二进制数据写入文件。 * DataOutputStream是OutputStream的另一个子类,它可以 * 连接到一个FileOutputStream上,便于写各种基本数据类型的数据。 */ public void writeMethod1() { String fileName="c:/kuka1.dat"; int value0=255; int value1=0; int value2=-1; try { //将DataOutputStream与FileOutputStream连接可输出不同类型的数据 //FileOutputStream类的构造函数负责打开文件kuka.dat,如果文件不存在, //则创建一个新的文件,如果文件已存在则用新创建的文件代替。然后FileOutputStream //类的对象与一个DataOutputStream对象连接,DataOutputStream类具有写 //各种数据类型的方法。 DataOutputStream out=new DataOutputStream(new FileOutputStream(fileName)); out.writeInt(value0); out.writeInt(value1); out.writeInt(value2); out.close(); } catch (Exception e) { e.printStackTrace(); } } //对于大量数据的写入,使用缓冲流BufferedOutputStream类可以提高效率 public void writeMethod2() { String fileName="c:/kuka2.txt"; try { DataOutputStream out=new DataOutputStream( new BufferedOutputStream( new FileOutputStream(fileName))); out.writeInt(10); System.out.println(out.size()+" bytes have been written."); out.writeDouble(31.2); System.out.println(out.size()+" bytes have been written."); out.writeBytes("JAVA"); System.out.println(out.size()+" bytes have been written."); out.close(); } catch (Exception e) { e.printStackTrace(); } } /** * 对二进制文件比较常见的类有FileInputStream,DataInputStream * BufferedInputStream等。类似于DataOutputStream,DataInputStream * 也提供了很多方法用于读入布尔型、字节、字符、整形、长整形、短整形、 * 单精度、双精度等数据。 */ public void readMethod1() { String fileName="c:/kuka1.dat"; int sum=0; try { DataInputStream in=new DataInputStream( new BufferedInputStream( new FileInputStream(fileName))); sum+=in.readInt(); sum+=in.readInt(); sum+=in.readInt(); System.out.println("The sum is:"+sum); in.close(); } catch (Exception e) { e.printStackTrace(); } } public void readMethod2() { try { FileInputStream stream=new FileInputStream("c:/kuka.dat"); int c; while((c=stream.read())!=-1) { System.out.println(c); } } catch (Exception e) { e.printStackTrace(); } } }
晕噢,格式全乱了~~
② java如何读取txt文件的内容
读取TXT文件内容在Java中并非难事,基本步骤如下:
TXT文件通常通过流方式读取。
Java提供FileInputStream类,使用文件路径或文件对象初始化流。
构造InputStreamReader,指定字符编码,以方便文本读取。
使用BufferedReader配合readLine方法,读取整行文本。
循环利用BufferedReader读取文件内容,完成所需操作。
流是Java中重要概念,理解流的使用至关重要。
新版本Java引入NIO API,简化文件读写。
对于JDK11及以上,读取文本文件非常简单。
对于JDK8,使用流按行读取文本内容。
注意:在读取文件时可能出现乱码问题,解决方法是使用类库Cpdetector并导入相关jar包或使用maven。
对于二进制读取,可选用DataInputStream或RandomAccessFile。
RandomAccessFile允许移动文件指针,适用于跳过字节或整体读取。
DataInputStream为纯粹的输入流。
处理大量数据时,考虑以下策略:
1. 使用ByteBuffer和堆外内存,避免OOM,适合内存充足情况。
2. 利用RandomAccessFile分块读取,记录读取位置,处理后继续读。
3. 多线程处理,将文件分割为多个块,分发至多个线程并发处理。
4. 使用BufferedReader与正则表达式匹配特征数据,处理后继续读取。
③ 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.length>MAXMESSAGELENGTH){ throw new IOException("message too long"); } //write length prefix out.write((message.length>>BYTEMASK)&BYTEMASK); out.write(message.length&BYTEMASK); //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 解析 txt 文件) 求高手
Java中解析文件的方法多种多样,这里介绍几个常用的方法,帮助您更好地处理文件内容。
首先,以字节为单位读取文件内容,这种方法常用于读取二进制文件,如图片、声音、影像等。代码示例如下:
java
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);
showAvailableBytes(in);
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) {
}
}
}
}
接下来,以字符为单位读取文件内容,这种方法常用于读取文本、数字等类型的文件。示例代码如下:
java
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) {
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));
while ((charread = reader.read(tempchars)) != -1) {
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) {
}
}
}
}
最后,以行为单位读取文件内容,这种方法适用于读取面向行的格式化文件。代码如下:
java
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;
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) {
}
}
}
}
以上三种方法各有特点,可根据实际需求选择合适的方法来解析文件内容。
⑤ java怎么实现读取一个文件,拿到二进制流
InputStream 就是读取二进制文件的, 任何文件都可以用这个流来读, 也叫字节输入流