Java의 FileInputStream 사용
-
22-07-2019 - |
문제
~ 안에 java.io.FileInputStream
, 방법이 있습니다 int read(Byte[] buffer,int offset,int numBytes)
; 이 기능을 사용할 수있는 방법 -이 방법과 read(byte[] buffer)
?
해결책
Javadoc에서 지적한 바와 같이 (및 매개 변수의 이름이 표시) 오프셋이있는 메소드 및 Numbytes는 버퍼의 일부만 사용하여 출력을 넣습니다.
public int read(byte[] b,
int off,
int len)
throws IOException
Parameters:
b - the buffer into which the data is read.
off - the start offset of the data.
len - the maximum number of bytes read.
이미 데이터가있는 기존 버퍼를 재사용하려면이 메소드를 사용할 수 있습니다. numBytes
시작 offset
덮어 쓰기).
Java에서는 버퍼의 거의 모든 작업이 이러한 종류의 인터페이스를 제공합니다. 제대로 사용하면 필요한 것보다 데이터를 복사/버퍼링하지 않아도됩니다.
다른 팁
방금 Javadoc에서 이것을 얻었습니다.
이 입력 스트림에서 바이트 배열로 LEN 바이트의 데이터를 읽습니다. Len이 0이 아닌 경우 방법은 일부 입력을 사용할 수있을 때까지 차단됩니다. 그렇지 않으면 바이트를 읽지 않고 0이 반환되지 않습니다.
매개 변수 :
- B- 데이터를 읽는 버퍼.
- OFF- 대상 배열 B에서 시작 오프셋
- LEN- 최대 바이트 수입니다.
반환 : 파일 끝에 도달했기 때문에 더 이상 데이터가없는 경우 버퍼에 읽는 총 바이트 수 또는 -1.
http://java.sun.com/javase/6/docs/api/java/io/fileinputstream.html#read (byte [, int, int)
이 기능은 전체 파일을 메모리로 읽는 데 매우 유용합니다. 이 예를 참조하십시오.
File = new File("/anywhere/anyfile");
InputStream is = new FileInputStream(file);
long fileSize = file.length();
byte[] bytes = new byte[(int)fileSize];
int offset = 0;
int count=0;
while (offset < fileSize) {
count=is.read(bytes, offset, fileSize-offset));
if (count >= 0)
offset += count;
else
throw new IOException("Can't read file "+file.getName());
}
is.close();
// Now bytes has all the complete file.
제휴하지 않습니다 StackOverflow