java FileInputStream 과 FileOutputStream 깊이 분석
7810 단어 자바
public native int read() throws IOException;
private native int readBytes(byte b[], int off, int len) throws IOException;
FileOutputStream 의 쓰기:
public native void write(int b) throws IOException;
private native void writeBytes(byte b[], int off, int len) throws IOException;
FileInputStream 과 FileOutputStream 에서 가장 많이 사용 되 는 곳 은 바로 파일 의 복사 과정 이다.다음은 두 가지 예 를 통 해 설명 하 겠 습 니 다. 예 1: 한 바이트 의 읽 기와 쓰기.
public class Test
{
public static void main(String[] args)
{
File src = new File("d:\\src.txt");
File dst = new File("d:\\dst.txt");
doSaveFile(src, dst);
}
public static void doSaveFile(File src, File dst)
{
InputStream in = null;
OutputStream out = null;
try
{
in = new FileInputStream(src);
out = new FileOutputStream(dst);
int len = 0;
while ((len = in.read()) > 0)
{//len
out.write(len);
}
}
catch (Exception e)
{
}
finally
{
if (null != in)
{
try
{
in.close();
}
catch (IOException e)
{
}
}
if (null != out)
{
try
{
out.close();
}
catch (IOException e)
{
}
}
}
}
}
예 2: 데이터 블록의 읽 기와 쓰기
public class Test
{
private final static int BUFFER_SIZE = 16 * 1024;
public static void main(String[] args)
{
File src = new File("d:\\src.txt");
File dst = new File("d:\\dst.txt");
doSaveFile(src, dst);
}
public static void doSaveFile(File src, File dst)
{
InputStream in = null;
OutputStream out = null;
try
{
in = new FileInputStream(src);
out = new FileOutputStream(dst);
byte[] buffer = new byte[BUFFER_SIZE];
int len = 0;
while ((len = in.read(buffer)) > 0)
{//len
out.write(buffer, 0, len);
}
}
catch (Exception e)
{
}
finally
{
if (null != in)
{
try
{
in.close();
}
catch (IOException e)
{
}
}
if (null != out)
{
try
{
out.close();
}
catch (IOException e)
{
}
}
}
}
}
의문: 위 에 두 가지 예 가 열거 되 어 있 는데 도대체 어떤 예 가 효율 이 더 높 습 니까?효율 적 인 비교 가 쉽 지 않 기 때문에 이 문 제 는 대답 하기 어 려 울 지도 모른다.그리고 데이터 흐름 의 밑바닥 이 실현 되 는 것 도 우리 가 알 기 어렵다.사실 이 문 제 를 떠 나 우 리 는 더 효율 적 인 읽 기 방식 이 있다. 그것 이 바로 다음 글 에서 말 하고 자 하 는 Buffered InputStream 과 Buffered OutputStream 이다.주의해 야 할 것 은 FileInputStream 인 스 턴 스 대상 을 만 들 때 지정 한 파일 은 존재 하고 읽 을 수 있어 야 합 니 다.FileOutputStream 인 스 턴 스 대상 을 만 들 때 지정 한 파일 이 존재 하면 이 파일 의 원래 내용 은 덮어 쓰 고 지 워 집 니 다.
다음으로 이동: FileInputStream 과 FileOutputStream 깊이 분석
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.