/**
* 將檔案轉換成byte陣列
* @param
* @return
*/
public static byte[] File2byte(File tradeFile){
byte[] buffer = null;
try
{
FileInputStream fis = new FileInputStream(tradeFile);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1)
{
bos.write(b, 0, n);
}
fis.close();
bos.close();
buffer = bos.toByteArray();
}catch (FileNotFoundException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
return buffer;
}
uj5u.com熱心網友回復:
function FileToByte(FileNamePath:String):TByteArray;var
aFileStream: TMemoryStream;
begin
aFileStream:= TMemoryStream.Create;
aFileStream.LoadFromFile(FileNamePath);
aFileStream.Position := 0;
aFileStream.ReadBuffer(Result,aFileStream.Size); //你要求好像是1024,那就把aFileStream.Size改為1024測驗一下
try
aFileStream.Free;
except
end;
end;
uj5u.com熱心網友回復:
不要那么復雜:uses System.Generics.Collections, System.IOUtils;
var
buf: TArray<byte>;
//...
buf := TFile.ReadAllBytes(檔案名);
Java的一大特點是把簡單問題復雜化(復雜問題也沒簡單多少)~
uj5u.com熱心網友回復:
varFs, FsTemp: TFileStream;
Byte_1024: array[0..1023] of Byte;
begin
Fs := TFileStream.Create('1.txt', fmOpenRead);
with Fs do
begin
Position := 0;
while Position < 1024 do
begin
Read(Byte_1024[Position], 1);
if Position=Size then
begin
Break;
end;
end;
end;
Fs.Free;
end;
我也來湊熱鬧下,沒有寫錯誤跳出~
uj5u.com熱心網友回復:
你們想多了,跟1024沒關系,byte[] b = new byte[1024];就是一個臨時緩沖區,因為它的兩個stream之間沒有copy方法,只能借助臨時緩沖區讀寫進行復制,而之所以要用兩個stream,也是因為FileInputStream就沒有toByteArray方法,所以必須:從FileInputStream讀入到臨時緩沖區
寫臨時緩沖區到ByteArrayOutputStream
呼叫ByteArrayOutputStream.toByteArray寫到一個位元組陣列
回傳位元組陣列
總之,java這套設計不但繁瑣,而且效率低下,好像老學究設計的,為自己的井井有條而自鳴得意~
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/261174.html
標籤:網絡通信/分布式開發
