java文件二進制文件
① 怎樣用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();
}
}
② 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是一門面向對象的編程語言,不僅吸收了C++語言的各種優點,還摒棄了C++里難以理解的多繼承、指針等概念,因此Java語言具有功能強大和簡單易用兩個特徵。Java語言作為靜態面向對象編程語言的代表,極好地實現了面向對象理論,允許程序員以優雅的思維方式進行復雜的編程。
④ 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中二進制的表示:
1、Java中定義兩個數,然後分別列印出它們的二進製表示(例如7和-7):
System.out.println("Java二進制7:"+Integer.toBinaryString(7));
System.out.println("Java二進制-7:"+Integer.toBinaryString(-7));
輸出:
Java二進制7: 111
Java二進制-7:
7的二進制就是111
-7轉化二進制的過程:
(1)把-7轉化成7,二進制是 111
(2)Java中對於不滿32位的int二進制自動補齊,所以變成了 (29個0)111
(3)然後取反 (29個1)000
(4)然後加1 (29個1)001
(5)java文件二進制文件擴展閱讀:
c語言中二進制的轉換:
用函數轉換itoa(值,數組名,進制)
#include<stdio.h>
#include<stdlib.h>
voidmain()
{
char str[8];
inti=8;
itoa(i,str,2);
printf("%s",str);
}
⑥ Java的Class位元組碼文件是二進制的嗎
Java的Class文件是有8個位元組為基礎的位元組流構成的,這些位元組流之間都嚴格按照規定的順序排列,並且位元組之間不存在任何空隙,對於超過8個位元組的數據,將按
照Big-Endian的順序存儲的,也就是說高位位元組存儲在低的地址上面,而低位位元組存儲到高地址上面,其實這也是class文件要跨平台的關鍵,因為
PowerPC架構的處理採用Big-Endian的存儲順序,而x86系列的處理器則採用Little-Endian的存儲順序,因此為了Class文
件在各中處理器架構下保持統一的存儲順序,虛擬機規范必須對起進行統一。
這些能被機器直接識別的就是二進制。
⑦ 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();
}