IO: FileInputStream 및 FileOutputStream

2530 단어 F#
FileInputStream과 FileOutputStream 클래스는 각각 디스크 파일의 입력 흐름과 출력 흐름 대상을 만들고, 구조 함수를 통해 파일 경로와 파일 이름을 지정합니다.FileInputStream 객체 인스턴스를 작성할 때 지정된 파일은 존재하고 읽을 수 있어야 하며, FileOutputStream 인스턴스 객체를 작성할 때 지정된 파일이 이미 있으면 해당 파일의 원래 내용이 덮어쓰여집니다.
FileInputStream 클래스를 만드는 디스크 파일의 Stream 객체에는 다음 두 가지 방법이 있습니다.
(1)FileInputStream fis = new FileInputStream("test.txt");
(2)File f = new File("test.txt");
    FileInputStream fis = new FileInputStream(f);
두 번째는test 파일에 대해 많은 File 클래스를 조작할 수 있다. 예를 들어 존재 여부, 쓰기 가능 여부 등이다.이것은 File 그 문장의 내용이다.
FileOutputStream 인스턴스 객체를 만들 때는 아직 존재하지 않는 파일 이름을 지정할 수 있지만 다른 프로그램에서 열 파일은 지정할 수 없습니다.
다음은 File OutputStream 클래스로 파일에 문자열을 쓴 다음 File InputStream으로 쓴 내용을 읽습니다.

import java.io.*;
public class FileStream {

    public static void main(String[] args) throws Exception{
        FileOutputStream out = new FileOutputStream("test.txt");
        out.write("www.cublog.com".getBytes());//     ,write()         ,          

        out.close();//        

        
        byte[] buf = new byte[1024];
        File f = new File("test.txt");
        FileInputStream in = new FileInputStream(f);
        int len = in.read(buf);//      

        System.out.println(new String(buf,0,len));
        in.close();
    }
}


Reader 클래스 및 Writer 클래스:
java의 문자는 유니코드로 인코딩된 두 바이트입니다.위의 File Input Stream과 File Output Stream은 모두 바이트를 처리하는 데 사용되며, 위의 문자열을 처리할 때 문자열을 바이트로 변환한 다음에 파일에 쓰고, 문자열을 읽을 때도 먼저 읽은 바이트 그룹을 문자열로 변환합니다.이것은 추가 바이트와 문자 사이의 변환 코드를 작성해야 한다.자바에는 입출력 장치에 문자를 입력하고 출력하는 데 사용되는 단독 클래스가 있습니다. 예를 들어 아까의 예는 FileReader와 FileWriter를 사용할 수 있습니다.
Reader 클래스와 Writer 클래스는 텍스트 파일을 읽는 데 사용되며 InputStream과 OutputStream은 이진 형식의 파일의 내용을 읽는 데 사용됩니다
위의 예는 텍스트 파일이므로 FileReader 및 FileWriter 클래스를 사용하여 다음과 같이 재정의할 수 있습니다.

import java.io.*;
public class FileStream {

    public static void main(String[] args) throws Exception{
              
        FileWriter out = new FileWriter("test.txt");
        out.write("www.cublog.com");
        out.close();
        
        char[] buf = new char[1024];
        FileReader in = new FileReader("test.txt");
        int len = in.read(buf);
        System.out.println(new String(buf,0,len));
        in.close();
        
    }
}


좋은 웹페이지 즐겨찾기