① 緊急求助!!!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 就是讀取二進制文件的, 任何文件都可以用這個流來讀, 也叫位元組輸入流