當前位置:學者齋 >

IT認證 >SUN認證 >

Java如何讀取文件內容再編輯

Java如何讀取文件內容再編輯

有時候,我們需要將讀取文件的.內容到一個byte[] 數組中,然後對這個數組進行一些修改,這時,我們可以藉助於ByteArrayOutputStream 這個類來實現。

Java如何讀取文件內容再編輯

ByteArrayOutputStream,顧名思義,同樣是一個OutputStream,那麼,對於它的寫入操作,和其他的 OutputStream應該是沒有什麼兩樣,寫入代碼可以説是隨手拈來的,與其他輸出流的不同之處在於,ByteArrayOutputStream寫入到內存中,並提供一個 toByteArray() 方法返回我們所需要的byte[]。

Java代碼

//保存上傳的附件信息

String filename = files[0];

String filepath = "upload/append/"+files[1];

BufferedInputStream in = new BufferedInputStream(new FileInputStream(filepath));

ByteArrayOutputStream out = new ByteArrayOutputStream(2048);

tln("available bytes"+lable());

byte[] temp = new byte[2048];

int size =0;

while((size = (temp))!=-1){ e(temp,0,size);

}

e();

byte[] content = teArray();

String stream = new BaseCode64()deBase64(content);

tln("content" +th);

effect += insertAttachmentInfo(conn,attNo,processId,filename,stream);

這裏把讀取的流以base64保存,使用了類BaseCode64()的方法EncodeBase64。

代碼如下:

Java代碼

package ;

import ArrayOutputStream;

public class BaseCode64 {

private String TableBase64;

private String FError;

public BaseCode64()

{

TableBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

FError = new String();

FError = "";

}

public String DecodeBase64(byte [] Value){

ByteArrayOutputStream o = new ByteArrayOutputStream();

byte d[] = new byte[4];

try

{

int count = 0;

byte x[] = Value;

do

{

if(count >= th)

{

break;

}

for(int n = 0; n <= 3; n++)

{

if(count >= th)

{

d[n] = 64;

} else

{

int y = xOf(x[count]);

if(y < 0)

{

y = 65;

}

d[n] = (byte)y;

}

count++;

}

e((byte)(((d[0] & 0x3f) << 2) + ((d[1] & 0x30) >> 4)));

if(d[2] != 64)

{

e((byte)(((d[1] & 0xf) << 4) + ((d[2] & 0x3c) >> 2)));

if(d[3] != 64)

{

e((byte)(((d[2] & 3) << 6) + (d[3] & 0x3f)));

}

}

} while(true);

}

catch(StringIndexOutOfBoundsException e)

{

FError = eOf(eOf(FError)) + eOf(eOf(ring()));

tln(ring());

}

return ring();

}

public String EncodeBase64(byte [] Value){

ByteArrayOutputStream o = new ByteArrayOutputStream();

byte d[] = new byte[4];

try

{

int count = 0;

for(byte x[] = Value; count < th;)

{

byte c = x[count];

count++;

d[0] = (byte)((c & 0xfc) >> 2);

d[1] = (byte)((c & 3) << 4);

if(count < th)

{

c = x[count];

count++;

d[1] = (byte)(d[1] + (byte)((c & 0xf0) >> 4));

d[2] = (byte)((c & 0xf) << 2);

if(count < th)

{

c = x[count];

count++;

d[2] = (byte)(d[2] + ((c & 0xc0) >> 6));

d[3] = (byte)(c & 0x3f);

} else

{

d[3] = 64;

}

} else

{

d[2] = 64;

d[3] = 64;

}

int n = 0;

while(n <= 3)

{

e(At(d[n]));

n++;

}

}

}

catch(StringIndexOutOfBoundsException e)

{

FError = eOf(eOf(FError)) + eOf(eOf(ring()));

tln(ring());

}

return ring();

}

}

標籤: JAVA 讀取 文件
  • 文章版權屬於文章作者所有,轉載請註明 https://xuezhezhai.com/zh-hk/itrz/sun/n1e05l.html