Home > Back-end >  Ask for help, the following Java function, how to implement in Delphi, lane for a long time, both si
Ask for help, the following Java function, how to implement in Delphi, lane for a long time, both si

Time:02-20

/* *
* the file into a byte array
* @ 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 ();
} the catch (FileNotFoundException e) {
e.printStackTrace();
} the catch (IOException e) {
e.printStackTrace();
}
The return buffer;
}

CodePudding user response:

The function FileToByte (FileNamePath: String) : TByteArray;
Var
AFileStream: TMemoryStream;
The begin
AFileStream:=TMemoryStream. Create;
AFileStream. LoadFromFile (FileNamePath);
AFileStream. Position:=0;
AFileStream. ReadBuffer (Result, aFileStream. Size);//as if you asked for 1024, then the aFileStream. Change the Size to 1024 test
Try
AFileStream. Free;
Except,
end;
end;

CodePudding user response:

Don't be so complicated:
USES the System. The Generics. Collections, System. IOUtils;

Var
Buf: TArray;
//...
Buf:=TFile. ReadAllBytes (filename);

Java is a feature of the simple complication (how many complicated problem didn't also simple) ~

CodePudding user response:

Var
Fs, FsTemp: TFileStream;
Byte_1024: an array of Byte [0.. 1023];
The begin
Fs:=TFileStream. Create (' 1. TXT ', fmOpenRead);
With Fs do
The begin
Position:=0;
While the Position & lt; 1024 do
The begin
Read (Byte_1024 [Position], 1);
If the Position=Size then
The begin
Break;
end;
end;
end;
Fs. Free;
end;
I do not help, didn't write error out ~

CodePudding user response:

Do you want to many, with 1024 it doesn't matter, byte [] b=new byte [1024]. Is a temporary buffer, because it's not copy method between the two stream, with only a temporary buffer, speaking, reading and writing to reproduce, and two stream is used, it is also because a FileInputStream toByteArray method, so you have to:
From a FileInputStream read into a temporary buffer
Write a temporary buffer to ByteArrayOutputStream
Call ByteArrayOutputStream. ToByteArray wrote a byte array
Returns an array of bytes
All in all, Java this design not only cumbersome, and inefficiencies, as if the old pedant design, in order for ourselves and complacent ~
  • Related