Java IO 일반 작업에 대한 자세한 설명(코드 예제)

개요

Java I/O 작업은 데이터 입/출력 작업을 말합니다.

Java의 I/O 작업 클래스는 java.io 패키지에 있으며 주로 다음 범주로 나뉩니다.

  • 바이트 연산 기반 I/O 인터페이스: InputStream 및 OutputStream
  • 문자 연산 기반 I/O 인터페이스: Writer 및 Reader
  • 디스크 작업 기반 I/O 인터페이스: 파일

1. 핵심 수업 소개

  • 바이트 기반 I/O 작업의 핵심은 모든 유형의 스트림 데이터를 작업할 수 있는 바이트 배열 byte[]를 작업하는 것입니다.
  • 문자 기반 I/O 연산, 핵심은 문자 배열 char[] 연산으로 문자형 스트림 데이터만 연산 가능, 비문자 스트림 데이터(사진, 동영상 등)인 경우 왜곡될 것이다

1. 바이트 입력 스트림

친절한 기능 설명하다
ByteArrayInputStream 메모리 버퍼를 InputStream으로 사용 FilterInputStream 개체에 연결하여 파일에 바이트 스트림을 저장합니다.
FileInputStream 파일에서 정보 읽기 파일 객체 파일을 입력 스트림으로 변환하여 파일의 데이터를 읽습니다.
FilterInputStream 다른 InputStream 클래스에 유용한 기능을 제공하는 데코레이터 인터페이스 역할을 하는 추상 클래스
버퍼링된 입력 스트림 IO 성능 향상을 위한 버퍼 작업 제공, 수신 입력 스트림에 대한 버퍼링 기능 추가 FilterInputStream 서브클래스
데이터 입력 스트림 DataOutputStream과 함께 사용되어 포팅된 방식으로 스트림에서 기본 데이터 유형을 읽습니다. 기본 데이터 유형을 읽기 위한 모든 인터페이스를 포함합니다. FilterInputStream 서브클래스

바이트 입력 스트림

2. 바이트 출력 스트림

친절한 기능 설명하다
ByteArrayOutputStream 메모리에 버퍼를 만듭니다. 스트림으로 전송된 모든 데이터는 이 버퍼에 배치됩니다. 입력 스트림을 바이트 배열로 변환하는 것이 편리합니다.
FileOutputStream 파일에 정보 쓰기
FilterOutputStream 다른 OutputStream에 유용한 기능을 제공하는 데코레이터 역할을 하는 인터페이스인 추상 클래스
버퍼링된 출력 스트림 IO 성능을 향상시키기 위해 버퍼 작업을 제공합니다. 들어오는 출력 스트림에 버퍼링 기능을 추가하고, flush()를 호출하여 버퍼를 지울 수 있습니다. FilterOutputStream 서브클래스
데이터 출력 스트림 DataInputStream과 함께 사용하면 기본 데이터 유형을 이식된 방식으로 스트림에 쓸 수 있습니다. 여기에는 기본 데이터 유형을 쓰기 위한 모든 인터페이스가 포함됩니다. FilterOutputStream 서브클래스

바이트 출력 스트림

3. 문자 입력 스트림

친절한 기능 설명하다
입력스트림리더 바이트 입력 스트림 InputStream을 문자 입력 스트림으로 변환
파일 판독기 파일 객체 File을 문자 입력 스트림으로 변환합니다. InputStreamReader의 하위 클래스
버퍼링된 리더 문자 입력 스트림 Reader의 동작 성능 향상을 위한 버퍼 기능 제공
문자열 판독기 문자열을 문자 스트림 작업으로 변환

문자 입력 스트림

4. 문자 출력 스트림

친절한 기능 설명하다
OutputStreamWriter 바이트 출력 스트림 OutputStream을 문자 출력 스트림으로 변환
FileWriter 파일 객체 File을 문자 출력 스트림으로 변환 OutputStreamWriter의 하위 클래스
BufferedWriter 문자 출력 스트림 Writer의 연산 성능 향상을 위한 버퍼 기능 제공
문자열 작성기 문자열을 문자 스트림 작업으로 변환

문자 출력 스트림

2. 주요 작업 소개

1. 스트림 닫기

try-with-resources모든 데이터 스트림은 작업이 완료된 후 close 메서드를 호출하여 닫아야 합니다.1.7 이상에서는 문을 사용하여 스트림을 사용하는 것이 좋습니다. 이렇게 하면 명시적으로 close() 메서드를 호출하지 않고 일부 반복 코드를 줄이고, 작업이 완료된 후 자동으로 close를 호출합니다.

try-with-resources문은 java.io.Closeable인터페이스를 구현하는 모든 하위 클래스 개체를 자동으로 닫을 수 있습니다.

 try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))) {
    
    
     bos.write(content.getBytes());
     bos.flush();
 }

2. 캐시 새로 고침

flush() 메서드는 OutputStream 개체가 내부 버퍼에 임시로 저장된 데이터를 즉시 쓰도록 강제하는 데 사용됩니다(일반적으로 이 메서드를 수동으로 호출할 필요가 없으며 실제 데이터는 내부 버퍼가 완료된 후 자동으로 실행됩니다) full. 쓰기 작업은 또한 close() 메서드를 호출할 때 자동으로 flush() 메서드를 호출합니다.)

3. 직렬화 스트림 및 역직렬화 스트림

객체의 직렬화는 객체를 바이트 시퀀스로 변환하는 것이고 그 반대의 경우 역직렬화(deserialization)라고 하며 ObjectOutputStream은 직렬화 스트림이고 ObjectInputStream은 역직렬화 스트림입니다.

동작할 객체는 직렬화 인터페이스 Serializable을 구현해야 하며, 특정 필드를 직렬화하지 않으려면 transient를 사용하여 해당 필드가 직렬화되지 않도록 필드를 수정하거나 다시 작성하여 수동으로 직렬화할 수 있습니다. 방법 writeObjectOverride().readObjectOverride()

모든 개체가 동일한 정적 변수 값을 공유하기 때문에 정적 변수도 직렬화할 수 없습니다.

1) ObjectOutputStream 직렬화 스트림

주요 메서드는 객체의 클래스, 클래스의 시그니처, 이 클래스와 그 부모 클래스에 있는 모든 비정적 및 비일시적 필드의 값을 저장하는 writeObject입니다.

public final void writeObject(Object obj) throws IOException {
    
    
    if (enableOverride) {
    
    
        writeObjectOverride(obj);
        return;
    }
    try {
    
    
        writeObject0(obj, false);
    } catch (IOException ex) {
    
    
        if (depth == 0) {
    
    
            writeFatalException(ex);
        }
        throw ex;
    }
}

2) ObjectInputStream 역직렬화 스트림

주요 메서드는 객체의 클래스, 클래스의 서명, 이 클래스와 해당 슈퍼클래스의 모든 비정적 및 비일시적 필드 값을 다시 읽는 readObject입니다.

    public final Object readObject()
        throws IOException, ClassNotFoundException
    {
    
    
        if (enableOverride) {
    
    
            return readObjectOverride();
        }

        // if nested read, passHandle contains handle of enclosing object
        int outerHandle = passHandle;
        try {
    
    
            Object obj = readObject0(false);
            handles.markDependency(outerHandle, passHandle);
            ClassNotFoundException ex = handles.lookupException(passHandle);
            if (ex != null) {
    
    
                throw ex;
            }
            if (depth == 0) {
    
    
                vlist.doCallbacks();
            }
            return obj;
        } finally {
    
    
            passHandle = outerHandle;
            if (closed && depth == 0) {
    
    
                clear();
            }
        }
    }

3. 코드 예시

import org.springframework.util.StopWatch;
import java.io.*;
public class FileUtilTest {
    
    
    /**
     * 复制文件
     */
    public static void copyFile(String fromFileName, String toFileName) throws Exception {
    
    
        File fromFile = new File(fromFileName);
        File toFile = new File(toFileName);
        StopWatch watch = new StopWatch("fileTest");
        watch.start("copy");

        if (!fromFile.exists()) {
    
    
            System.out.println("源文件不存在");
            System.exit(1);
        }
        if (!toFile.getParentFile().exists()) {
    
    
            toFile.getParentFile().mkdirs();
        }

        try (InputStream is = new FileInputStream(fromFile);
             OutputStream os = new FileOutputStream(toFile)) {
    
    
            int temp = 0;
            byte[] data = new byte[4096];

            while ((temp = is.read(data)) != -1) {
    
    
                os.write(data, 0, temp);
            }
            watch.stop();
            System.out.println(watch.prettyPrint());
        }
    }

    /**
     * 通过字符流将字符串写入到文件中
     */
    public static void write(String fileName, String content) throws IOException {
    
    

        File file = new File(fileName);
        if (!file.getParentFile().exists()) {
    
    
            file.getParentFile().mkdirs();
        }
        try (Writer out = new FileWriter(file)) {
    
    
            out.write(content);
            out.flush();
        }
    }

    /**
     * 通过字节流将字符串写入到文件中,增加缓冲区功能
     */
    public static void writeBuffer(String fileName, String content) throws IOException {
    
    
        File file = new File(fileName);
        if (!file.getParentFile().exists()) {
    
    
            file.getParentFile().mkdirs();
        }
        try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))) {
    
    
            bos.write(content.getBytes());
            bos.flush();
        }
    }

    /**
     * 通过字符流将字符串写入到文件中,增加缓冲区功能
     */
    public static void writeBufferedWriter(String fileName, String content) {
    
    
        File file = new File(fileName);
        if (!file.getParentFile().exists()) {
    
    
            file.getParentFile().mkdirs();
        }
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
    
    
            bw.write(content);
            bw.flush();
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
    }

    /**
     * 通过字符流,从文件中读取字符串内容
     */
    public static void readChar(String fileName) {
    
    
        File file = new File(fileName);
        if (!file.exists()) {
    
    
            return;
        }
        try (Reader in = new FileReader(file)) {
    
    
            char[] data = new char[4096];
            int len;
            StringBuilder sb = new StringBuilder();
            while ((len = in.read(data)) != -1) {
    
    
                sb.append(new String(data, 0, len));
            }
            in.close();
            System.out.println(sb);
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }

    }

    /**
     * 通过字节流,从文件中读取字符串内容
     */
    public static void readByte(String fileName) throws IOException {
    
    
        File file = new File(fileName);
        if (!file.exists()) {
    
    
            return;
        }
        try (InputStream in = new FileInputStream(file)) {
    
    
            byte[] data = new byte[4096];
            int len;
            StringBuilder sb = new StringBuilder();
            while ((len = in.read(data)) != -1) {
    
    
                sb.append(new String(data, 0, len));
            }
            System.out.println(sb);
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
    }

    /**
     * 通过字符流,从文件中读取字符串内容,增加缓冲区功能
     */
    public static void readBufferReader(String fileName) throws Exception {
    
    
        File file = new File(fileName);
        if (!file.exists()) {
    
    
            return;
        }
        try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) {
    
    
            String line;
            while ((line = bufferedReader.readLine()) != null) {
    
    
                System.out.println(line);
            }
        }

    }

    /**
     * 通过字节流,从文件中读取字符串内容,增加缓冲区功能
     */
    public static void readBuffer(String fileName) throws Exception {
    
    
        File file = new File(fileName);
        if (!file.exists()) {
    
    
            return;
        }
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
    
    
            int len;
            byte[] data = new byte[4096];
            while ((len = bis.read(data)) != -1) {
    
    
                System.out.println(new String(data, 0, len));
            }
        }
    }

    /**
     * 将文件内容转换成字节数组
     */
    public static byte[] file2OutStream(String fileName) throws Exception {
    
    
        File file = new File(fileName);
        if (!file.exists()) {
    
    
            return null;
        }
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
             ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
    
    
            int len;
            byte[] data = new byte[4096];
            while ((len = bis.read(data)) != -1) {
    
    
                bos.write(data, 0, len);
            }
            return bos.toByteArray();
        }
    }

    /**
     * 将Java对象序列化存储在到文件中
     */
    public static void objWrite(String fileName) {
    
    
        File file = new File(fileName);
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))) {
    
    
            oos.writeObject("Hello ,World");
            oos.writeBoolean(false);
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
    }

    /**
     * 从序列化文件中反序列化出Java对象
     */
    public static void objRead(String fileName) {
    
    
        File file = new File(fileName);
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
    
    
            Object o = ois.readObject();
            System.out.println(o.getClass());
            System.out.println("o = " + o);
            System.out.println("ois.readBoolean() = " + ois.readBoolean());
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
    }

}

추천

출처blog.csdn.net/wlddhj/article/details/130090230