導航:首頁 > 編程語言 > java二進制寫入文件

java二進制寫入文件

發布時間:2022-06-08 06:21:12

『壹』 java中如何生成二進制文件比如我需要寫入0x123456 但是如果使用bufferedwriter的write() 只能寫入int...

java里對文件流分為位元組流和字元流。
1,FileOutputStream:按位元組寫入文件
2.1,導入包
import java.io.*;
2.2,聲明一個OutputStream引用
OutputStream out =null;
2.3,構造一個OutputStream對象,並在其中寫入內容
try {
out = new FileOutputStream("b.txt");
String str ="java終於完了";
byte[] b = str.getBytes();
try {
out.write(b, 0, b.length);
}
catch (IOException ex1) {
ex1.printStackTrace();
}
2.4,關閉對象
finally{
try {
out.close();
}
catch (IOException ex2) {
ex2.printStackTrace();
}
}
望採納!

『貳』 怎樣用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的api里沒有更改局部信息的輸出流,必須讀到內存重新寫到文件里,可以選擇覆蓋或追加,輸出流可以到jdk文檔里參考OutputStream類。

『肆』 緊急求助!!!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寫二進制文件,不能直接編輯,該怎麼操作

一直以來都在用java編程,以前在Java寫一些二進制格式的文件,就用DataOutputStream很方法,例如它的writeInt,writeLong等,我今天在看一些代碼的時候發現DataOutputStream在處理多位元組的數字的時候,使用的是BIG_ENDIAN(即將高位的位元組放在內存地址的低地址上),相應的DataInputStream的讀取方式也使用的是BIG_ENDIAN。

這樣就引出一個問題,如果我是用Java之外的語言,比如C語言讀取由DataOutputStream生成的文件,而平台正好是LITTLE_ENDIAN(用得很廣泛的x86的系統都是LITTLE_ENDIAN),很可能會造成數據錯誤,除非在C程序中自己重新按照BIG_ENDIAN的格式組裝int或者long.

這樣我們需要在寫文件的時候就按照平台的位元組順來寫,而ByteBuffer已經考慮到了這一點。

java.nio.ByteBuffer默認是BIG_ENDIAN(這可能和ByteBuffer主要用來做網路通訊有關),但是這個值是可以修改的。

比較使用DataOutputStream和ByteBuffer寫文件的差異:

public static void main(String[] args) throws IOException {
int _int = 12345678;
ByteBuffer _nbuffer = ByteBuffer.allocate(4);
_nbuffer.order(ByteOrder.nativeOrder()); //將新建的ByteBuffer設置為本機的位元組順
_nbuffer.putInt(_int);
_nbuffer.flip();

FileOutputStream _fou = new FileOutputStream("test_dout.data");
FileOutputStream _nfou = new FileOutputStream("test_nbuf.data");
DataOutputStream _dou = new DataOutputStream(_fou);

_dou.writeInt(_int);
_dou.close();

_nfou.write(_nbuffer.array());
_nfou.close();
System.out.println(ByteOrder.nativeOrder());
}

執行上面的代碼生成兩個文件:

test_dout.data - 使用DataOutputStream生成的BIG_ENDIAN文件,

test_nbuf.data - 使用ByteBuffer生成的主機位元組順的文件(此處的主機位元組順為LITTLE_ENDIAN)

使用下面的C程序分別讀取這兩個文件:

#include <stdio.h>
int read_file(char* file);
main()
{
char* dout = "test_dout.data";
char* nbuf = "test_nbuf.data";
printf("data in %s:%d\n",dout,read_file(dout));
printf("data in %s:%d\n",nbuf,read_file(nbuf));
}
int read_file(char* file)
{
FILE *fp;
int dat[1];
fp=fopen(file, "rb");/*打開一個二進制文件只讀*/
fread(dat, sizeof(int), 1, fp);
fclose(fp);
return dat[0];
}

編譯並執行:

gcc a.c

./a.out
data in test_dout.data:1315027968
data in test_nbuf.data:12345678

上面的C程序從test_dout.data取得的int數值是錯誤的,而從test_nbuf.data是正確的。

ByteBuffer不方便的地方在於它的大小不能自動擴展,但是也是可以解決的,比如MINA自己的ByteBuffer就支持自成擴展。

Java的生成二進制數據文件,應該要考慮一下位元組順的問題,以適應一些特殊的需求,比如多語言平台編程的情況。

『陸』 java以二進制傳輸字元集填啥

用UTF-8.
java讀寫文件的有很多種方式,基本都是採用java.io的inputStream和各種基於inputstream的封裝實現對文件的讀寫,最原始的介面提供的便是基於byte的讀寫,而String可以看做是char[],一個char是8個byte。在最原始的ASCII編碼中,我們採用一個位元組 也就時8位來表示一個字元(圖形字元或者控制字元),而後來1個位元組不足以表示現實中的所有字元,於是出現了各種各樣的編碼格式,常見的比如UTF-8,GBK,UNICODE等。java中的string也是遵循jre中定義的默認字元集(基本為UTF-8),而在byte[]轉化成String的過程中可能會由於編碼字元集問題導致String逆向回來的byte[]與原來的數組不一致。

『柒』 Java怎麼解析用C寫入的.bin類型二進制文件

Java怎麼解析用C寫入的.bin類型二進制文件
\\假設文件的地址為a.txt
FileInputStream in=new FileInputStream(new File("a.txt"));
byte[] buffer=new byte[4096];
int offset=0;
while((offset=in.read(buffer)>-1){
//這已經把文件讀入到buffer中了,范圍為0到offset,你可以做任何處理了

}
in.close();

『捌』 如何用Java向文件中寫入二進制代碼

FileOutputStream,這個類似乎是用來輸出圖像文件格式的,應該也可以操作二進制文件……

『玖』 java把01字元串當二進制寫入文件

outputstream的write方法要求傳入的時byte[]數組,如果你的01字串是String類型的的話,需要將其轉換成byte[],具體辦法可以看下面的例子:

publicstaticvoidmain(String[]args)

{

System.out.println("HelloWorld!");

Stringtext="10101010010001100111001";

Filef=newFile("/Users/hujia/Documents/test.txt");

OutputStreamos=null;

try{

os=newFileOutputStream(f);

os.write(text.getBytes());

}catch(FileNotFoundExceptione){

//TODOAuto-generatedcatchblock

e.printStackTrace();

}catch(IOExceptione){

//TODOAuto-generatedcatchblock

e.printStackTrace();

}finally{

try{

os.close();

}catch(IOExceptione){

//TODOAuto-generatedcatchblock

e.printStackTrace();

}

}

}
閱讀全文

與java二進制寫入文件相關的資料

熱點內容
信號分析pdf 瀏覽:925
暴力刪除命令 瀏覽:803
qt如何編譯加快速度 瀏覽:903
php添加數據sql語句 瀏覽:717
免費的小說app有什麼 瀏覽:405
螺桿壓縮機進氣閥動畫 瀏覽:651
兩台伺服器如何做負載均衡 瀏覽:227
程序員的工資是漲的嗎 瀏覽:813
視頻存儲伺服器可以干什麼 瀏覽:463
創建文件夾安裝失敗怎麼回事 瀏覽:832
程序員高考隔了幾年 瀏覽:822
雲伺服器是哪一層 瀏覽:22
jit編譯器的jit什麼意思 瀏覽:330
我想清理手機中空白文件夾 瀏覽:976
電腦e盤文件夾刪不掉怎麼辦 瀏覽:607
外圓凹圓弧編程 瀏覽:461
html5編程題 瀏覽:839
乾燥機製冷壓縮機一開就跳動 瀏覽:388
吉林壓縮空氣流量監測 瀏覽:618
根據地址獲取經緯度php 瀏覽:13