當前位置:首頁 » 編程語言 » java文件二進制

java文件二進制

發布時間: 2022-05-26 23:29:48

『壹』 java中二進制怎麼表示

二進制是計算技術中廣泛採用的一種數制。二進制數據是用0和1兩個數碼來表示的數。它的基數為2,進位規則是「逢二進一」,借位規則是「借一當二」,由18世紀德國數理哲學大師萊布尼茲發現。當前的計算機系統使用的基本上是二進制系統,數據在計算機中主要是以補碼的形式存儲的。計算機中的二進制則是一個非常微小的開關,用「開」來表示1,「關」來表示0。
1、Java中定義兩個數,然後分別列印出它們的二進製表示:
System.out.println("Java二進制7: "+Integer.toBinaryString(7));
System.out.println("Java二進制-7: "+Integer.toBinaryString(-7));
輸出:
Java二進制7:
111
Java二進制-7:

可以看到Java中對於數的表示屬於有符號的,那麼這個是怎麼來的?
7好辦,直接是111
-7轉化二進制的過程:
(1)把-7轉化成7,二進制是
111
(2)Java中對於不滿32位的int二進制自動補齊,所以變成了
(29個0)111
(3)然後取反
(29個1)000
(4)然後加1
(29個1)001
這就是-7的整個轉化過程,那麼現在有一個問題,如果有一個文本文件,每一行有八位二進制,表示的范圍是(0~255),也就是用一個位元組表示的無符號整數,如果現在要把這些二進制轉化成整數存到文件里應該怎麼做?
文件:
line1

11111110

(254)
line2

00000000

(0)
假設用Java讀進了第一行,那麼直接列印出來的值是-2,不符合要求,這時讓-2變254有兩種辦法:
(1)用Java自帶的方法,Byte.toUnsignedInt((byte)
-2)(ps.-2的二進製表示就是line1),這樣列印出來的就是254了
System.out.println(Byte.toUnsignedInt((byte) -2));
輸出:254
第二種方法的原理:
Java中-2的二進製表示:(這個二進制的後八位就是line1,可以直接列印的話Java把其當做了負數
-2)
Java中255的二進製表示:(24個『0』,8個『1』)
做與後變為:
這樣做與後表示的數就是正數了
254。可以想一下,假設每一行用2個位元組表示一個無符號數,那麼可以把每一行變成正整數用方法2怎麼做?
2.Java中的>>和>>>
'>>'
算術右移,向右移左邊補符號位
'>>>'
邏輯右移,向右移左邊補0
System.out.println("Java二進制-7: "+Integer.toBinaryString(-7));
System.out.println("-7>>2: "+Integer.toBinaryString(-7>>2));
System.out.println("-7>>>2: "+Integer.toBinaryString(-7>>>2));輸出:
Java二進制-7:
-7>>2:
-7>>>2: //正常應該這樣(00)左邊的兩個0不顯示

『貳』 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編譯器把java程序編譯成虛擬機可以識別的二進制代碼,稱為什麼

由java編譯器把源文件編譯成虛擬機可以識別的二進制代碼稱為位元組碼。

而位元組碼是由java解釋器去解釋執行的。

『肆』 java中什麼是能夠在計算機CPU上執行的二進制代碼

java中的JVM是能夠在計算機CPU上執行的二進制代碼。

  • java的執行過程

Java代碼需要經過編譯和解釋兩個步驟,才在能在平台上運行。首先java語言的編譯器,幫java代碼編譯成class的位元組碼,之後通過java虛擬機(JVM)來解釋執行。

  • java代碼的編譯

java代碼是如何編譯的?

首先編譯的解釋:把用高級程序設計語言書寫的源程序,翻譯成等價的計算機匯編語言或機器語言書寫的目標程序的翻譯程序。編譯的具體過程,可以看看《編譯原理》相關的書籍。

其實java的編譯過程,和通常c/c++還是不同的。

java編譯後的位元組碼文件格式主要分為兩部分:常量池和方法位元組碼。常量池記錄的是代碼出現過的所有token(類名,成員變數名等等)以及符號引用(方法引用,成員變數引用等等);方法位元組碼放的是類中各個方法的位元組碼。

Java編譯器卻不將對變數和方法的引用編譯為數值引用,也不確定程序執行過程中的內存布局,而是將些符號引用信息保留在位元組碼中,由解釋器在運行過程中創立內存布局,然後再通過查表來確定一個方法所在的地址,這樣就有效地保證了java的可移植性和安全性。

c/c++的編譯,當C編譯器編譯生成一個對象的代碼時,該代碼是為在某一特定硬體平台運行而生成的。因此在編譯過程中,編譯程序通過查表將所有對符號的引用轉換為特定的內存偏移量,以保證程序運行。

  • java虛擬機(JVM)

簡單的可以這樣理解它的功能:就是將java編譯之後的位元組碼,解釋成cpu能夠執行的二進制代碼。

JVM是一個虛構出來的計算機,是通過在實際的計算機上模擬模擬各種計算機功能來實現的。JVM有自己完善的硬體架構,如處理器、堆棧、寄存器等,還具有相應的指令系統。JVM的主要工作是解釋自己的指令集(即位元組碼)並映射到本地的CPU的指令集或OS的系統調用。Java語言是跨平台運行的,其實就是不同的操作系統,使用不同的JVM映射規則,讓其與操作系統無關,完成了跨平台性。JVM對上層的Java源文件是不關心的,它關注的只是由源文件生成的類文件(class file)。類文件的組成包括JVM指令集,符號表以及一些補助信息。

java虛擬機工作的原理,可以自己找一下網上的資料。大家還需要思考的問題,jvm的內存、jvm的垃圾回收(GC)、Android的朋友還要區分(Dalvik 和標准 Java 虛擬機JVM)的區別。

  • 總結:

java代碼編譯之後,可以直接運行在Windows或者其它裝有JVM虛擬機的系統下。而C或C++直接編譯成與機器和操作系統相關的代碼。所以C語言編譯的程序沒有跨平台性,就算沒有使用到操作系統相關的API,在不同的系統下也必須重新編譯才能運行。

『伍』 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讀取二進制文件

思路:按照位元組讀取文件到緩沖,然後對文件內容進行處理。

代碼如下:


publicstaticvoidreadFile()throwsIOException{
RandomAccessFilef=newRandomAccessFile("test.txt","r");
byte[]b=newbyte[(int)f.length()];
//將文件按照位元組方式讀入到位元組緩存
f.read(b);
//將位元組轉換為utf-8格式的字元串
Stringinput=newString(b,"utf-8");
//可以匹配到所有的數字
Patternpattern=Pattern.compile("\d+(\.\d+)?");
Matchermatch=pattern.matcher(input);
while(match.find()){
//match.group(0)即為你想獲取的數據
System.out.println(match.group(0));
}
f.close();
}

『柒』 java里怎樣把文件轉換成二進制

轉換文件成為二進制數據並保存的Java代碼:

取出數據並還原文件到本地的java代碼:

[java]view plain//讀取資料庫二進制文件

publicvoidreaderJpg()throwssqlException

{

connection=connectionManager.getconn();//自己連接自己的資料庫

StringsqlString="selectimagesfromsave_imagewhereid=4";//從資料庫中讀出要還原文件的二進制碼,這里我讀的是自己的資料庫id為4的文件

Filefile=newFile("E:\1.jpg");//本地生成的文件

if(!file.exists())

{

try{

file.createNewFile();

}catch(Exceptione){

e.printStackTrace();

}

}

try{

byte[]Buffer=newbyte[4096*5];

statement=connection.prepareStatement(sqlString);

resultSet=statement.executeQuery();

if(resultSet.next())

{

FileOutputStreamoutputStream=newFileOutputStream(file);

InputStreamiStream=resultSet.getBinaryStream("images");//去欄位用getBinaryStream()

intsize=0;

while((size=iStream.read(Buffer))!=-1)

{

System.out.println(size);

outputStream.write(Buffer,0,size);

}

}

}catch(Exceptione){

e.printStackTrace();

}

}

『捌』 Java 一個文件裡面存儲的是二進制數據 讀取出來以字元串形式展示

不需要轉換。
解釋:任何文件的存儲都是通過二進制的形式進行存儲的,只不過經過機器語言編譯後,展示給用戶的體驗是中文或者是字元串形式。
備註:如果是想將數字轉換為二進制,可以直接通過Integer的toBinaryString方法直接進行轉換,舉例:
int i =8;
System.out.println(Integer.toBinaryString(i));
輸出結果就是:1000.

『玖』 怎樣用Java讀寫二進制文件

import java.util.*;
import java.io.*;

class SmallFile {
static final int HEADLEN = 24; //頭總長度
byte[] fileName = new byte[16]; //列表文件名1: 長度128 想把它讀到char[]里 它的編碼方式不是Unicode。在不確定編碼方式的時候,最好直接用byte[]來存放
int offset; //列表文件地址1: 長度32 想把它讀到int里
int length = -1; //列表文件長度1: 長度32 想把它讀到int里
byte[] content;
public SmallFile() {

}

public SmallFile(byte[] fn, byte[] content) {
Arrays.fill(fileName, (byte) 0);
if (fn != null) {
if (fn.length <= 16) {
System.array(fn, 0, fileName, 0, fn.length);
}
else {
System.array(fn, 0, fileName, 0, 16);
}
}
this.content = content;
if (content != null) {
this.length = content.length;
}
else {
this.length = -1;
}
}
}

public class ReadBinary {
static final int HEADLEN = 8; //頭總長度
private String filename;
private byte[] filehead = new byte[4]; //文件頭: 長度32 想把它讀到char[]里 它的編碼方式不是Unicode
private int filecount = -1; //列表長度: 長度32 想把它讀到int里 假設他是3 就會有3個列表文件名
private List<SmallFile> files = null;

public void setFilehead(byte[] fh) {
if (fh == null)
return;
Arrays.fill(filehead, (byte) 0);
if (fh.length <= 4) {
System.array(fh, 0, filehead, 0, fh.length);
}
else {
System.array(fh, 0, filehead, 0, 4);
}
}

public ReadBinary(String filename) {
try {
readFromFile(filename);
}
catch (Exception ex) {
System.out.println(ex.getMessage());
System.out.println("在載入數據文件時失敗,因此視同為新建一個數據文件!");
this.filename = filename;
Arrays.fill(filehead, (byte) 0);
filecount = 0;
files = new ArrayList<SmallFile> ();
}
}

public void readFromFile(String filename) throws Exception {
BufferedInputStream bin = new BufferedInputStream(new FileInputStream(
filename));
this.filename = filename;
DataInputStream in = new DataInputStream(bin);
in.read(filehead); //文件頭: 長度32 想把它讀到char[]里 它的編碼方式不是Unicode
filecount = in.readInt(); //列表長度: 長度32 想把它讀到int里 假設他是3 就會有3個列表文件名
if (files == null) {
files = new ArrayList<SmallFile> ();
}
else {
files.clear();
}
for (int i = 0; i < filecount; i++) {
SmallFile file = new SmallFile();
in.read(file.fileName);
file.offset = in.readInt(); //列表文件地址1: 長度32 想把它讀到int里
file.length = in.readInt(); //列表文件長度1: 長度32 想把它讀到int里
files.add(file);
}
}

public void writeToFile() throws Exception {
String temp = filename + ".tmp"; //臨時文件
boolean exists = false;
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(filename, "r"); //文件存在則從文件讀入
exists = true;
}
catch (Exception ex) {
System.out.println("文件不存在,因此啟用內存寫入模式");
}
if (filecount != files.size()) {
throw new Exception("怪事,居然不相同??");
}
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new
FileOutputStream(temp)));
//1、寫總文件頭
out.write(filehead);
out.writeInt(filecount);
//2、寫列表頭
int sumlength = 0;
for (int i = 0; i < files.size(); i++) {
SmallFile file = files.get(i);
out.write(file.fileName);
if (file.length < 0) {
throw new Exception("怪事,文件長度怎麼可能小於0?");
}
else {
out.writeInt(ReadBinary.HEADLEN + SmallFile.HEADLEN * filecount +
sumlength);
sumlength += file.length;
out.writeInt(file.length);
}
}
//3、寫文件內容
for (int i = 0; i < files.size(); i++) {
SmallFile file = files.get(i);
if (file.content != null && (file.length == file.content.length)) {
out.write(file.content);
}
else if (exists) {
raf.seek(file.offset);
byte[] b = new byte[file.length];
raf.read(b);
System.out.println("b:" + new String(b));
out.write(b);
}
else {
throw new Exception("怪事,又不能從內存讀,又不能從文件讀。這活沒法幹了!");
}
}

out.close();
if (raf != null) {
raf.close();
raf = null;
}
System.gc();
//把原先的文件刪除
File f = new File(filename);
f.delete();
//再把臨時文件改名到正式文件
File f2 = new File(temp);
f2.renameTo(f);
}

public void addFile(SmallFile file) {
if (files != null) {
filecount++;
files.add(file);
}
}

public static void test1(){
ReadBinary rb = new ReadBinary("f:\\temp\\rb.dat");
rb.setFilehead("".getBytes());
SmallFile f = new SmallFile("第1個文件".getBytes(), "第1個文件的內容".getBytes());
rb.addFile(f);
try {
rb.writeToFile();
}
catch (Exception ex) {
ex.printStackTrace();
}
}

public static void test2(){
ReadBinary rb = new ReadBinary("f:\\temp\\rb.dat");
rb.setFilehead("HEA".getBytes());
SmallFile f = new SmallFile("第2個文件".getBytes(), "第2個文件的內容".getBytes());
rb.addFile(f);
try {
rb.writeToFile();
}
catch (Exception ex) {
ex.printStackTrace();
}
}

public static void main(String[] args) {
//test1();
test2();
}
}

熱點內容
簡易編程語言 發布:2025-02-12 18:48:07 瀏覽:522
咋上傳視頻 發布:2025-02-12 18:45:50 瀏覽:287
python的包機制 發布:2025-02-12 18:45:49 瀏覽:447
sqlserver網路實用工具 發布:2025-02-12 18:38:56 瀏覽:766
劍與家園新伺服器什麼時候轉國 發布:2025-02-12 18:38:05 瀏覽:433
php發送email 發布:2025-02-12 18:38:02 瀏覽:296
掃描二維碼密碼多少 發布:2025-02-12 18:23:35 瀏覽:51
北京時間ftp 發布:2025-02-12 18:23:31 瀏覽:777
開源分布式文件存儲 發布:2025-02-12 18:22:54 瀏覽:632
安卓七騎士亞服哪裡下載 發布:2025-02-12 18:22:49 瀏覽:532