ソースコード学Javaベース:InputStream、OutputStream、FileInputStream、FileOutputStream

9286 ワード

1. InputStream


1.1説明
InputStreamは抽象的なクラスです.具体的には:
This abstract class is the superclass of all classes representing an input stream of bytes.
主なサブクラスは次のとおりです.
AudioInputStream, ByteArrayInputStream, FileInputStream, FilterInputStream, InputStream, ObjectInputStream, PipedInputStream, SequenceInputStream, StringBufferInputStream
1.2コンストラクタ
その構造関数は非常に簡単で、無パラメトリック構造関数は1つしかありません.
  public InputStream() {}

1.3主な方法
その主な方法は前編で紹介したBufferedReaderと同様で,詳細な説明はしない.
int	available()
Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.
void	close()
Closes this input stream and releases any system resources associated with the stream.
void	mark(int readlimit)
Marks the current position in this input stream.
boolean	markSupported()
Tests if this input stream supports the mark and reset methods.
abstract int	read()
Reads the next byte of data from the input stream.
int	read(byte[] b)
Reads some number of bytes from the input stream and stores them into the buffer array b.
int	read(byte[] b, int off, int len)
Reads up to len bytes of data from the input stream into an array of bytes.
void	reset()
Repositions this stream to the position at the time the mark method was last called on this input stream.
long	skip(long n)
Skips over and discards n bytes of data from this input stream.

2. OutputStream


2.1説明
InputStreamと同様にOutputStreamも抽象クラスです.
This abstract class is the superclass of all classes representing an output stream of bytes. An output stream accepts output bytes and sends them to some sink.
2.2コンストラクタ
デフォルトの非パラメトリックコンストラクション関数は1つだけです.
OutputStream() 

2.3主な方法
void	close()
Closes this output stream and releases any system resources associated with this stream.
void	flush()
Flushes this output stream and forces any buffered output bytes to be written out.
void	write(byte[] b)
Writes b.length bytes from the specified byte array to this output stream.
void	write(byte[] b, int off, int len)
Writes len bytes from the specified byte array starting at offset off to this output stream.
abstract void	write(int b)
Writes the specified byte to this output stream.

3. FileInputStream


3.1説明
FileInputStreamはInputStreamのサブクラスであり、ファイルの読み取りを実現している.
A FileInputStream obtains input bytes from a file in a file system. What files are available depends on the host environment.FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader.
簡単な翻訳:
FileInputStreamファイルからバイトを読み込むのは、バイナリデータの読み取りに適しています.文字ファイルを読み込む場合は、FileReaderを使用するのが望ましいです.
FileReader次編でまたお話しします.
3.2コンストラクタ
FileInputStream(File file)
Creates a FileInputStream by opening a connection to an actual file, the file named by the File object file in the file system.
FileInputStream(FileDescriptor fdObj)
Creates a FileInputStream by using the file descriptor fdObj, which represents an existing connection to an actual file in the file system.
FileInputStream(String name)
Creates a FileInputStream by opening a connection to an actual file, the file named by the path name name in the file system.

3つのコンストラクション関数があります.パラメータはファイル、ファイル記述子、文字列です.主な使用方法は次のとおりです.
FileInputStream fis = new FileInputStream("d:/123.txt");
FileInputStream fis1 = new FileInputStream(new File("d:/123.txt"));

ファイルディスクリプタはあまり使われていません.私もできません.ソースコードを見ると、文字列がデフォルトでファイルに構成されていることがわかります.
  public FileInputStream(String paramString)
    throws FileNotFoundException
  {
    this(paramString != null ? new File(paramString) : null);
  }
  
  public FileInputStream(File paramFile)
    throws FileNotFoundException
  {
    String str = paramFile != null ? paramFile.getPath() : null;
    SecurityManager localSecurityManager = System.getSecurityManager();
    if (localSecurityManager != null) {
      localSecurityManager.checkRead(str);
    }
    if (str == null) {
      throw new NullPointerException();
    }
    if (paramFile.isInvalid()) {
      throw new FileNotFoundException("Invalid file path");
    }
    this.fd = new FileDescriptor();
    this.fd.incrementAndGetUseCount();
    this.path = str;
    open(str);
  }

どちらのコンストラクション関数もFileNotFoundExceptionを放出しますが、文字列がnullの場合、空のポインタ異常も放出されます.
3.3主な方法
int	available()
Returns an estimate of the number of remaining bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.
void	close()
Closes this file input stream and releases any system resources associated with the stream.
protected void	finalize()
Ensures that the close method of this file input stream is called when there are no more references to it.
FileChannel	getChannel()
Returns the unique FileChannel object associated with this file input stream.
FileDescriptor	getFD()
Returns the FileDescriptor object that represents the connection to the actual file in the file system being used by this FileInputStream.
int	read()
Reads a byte of data from this input stream.
int	read(byte[] b)
Reads up to b.length bytes of data from this input stream into an array of bytes.
int	read(byte[] b, int off, int len)
Reads up to len bytes of data from this input stream into an array of bytes.
long	skip(long n)
Skips over and discards n bytes of data from the input stream.

主な方法はBufferedReaderと同じです.簡単なコードの例を次に示します.
	public static void main(String[] args) {
		try {
			FileInputStream fis = new FileInputStream("d:/123.txt");
			byte[] b = new byte[1000 * 20];
			fis.read(b);
			System.out.println(new String(b));
			fis.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

通常、FileInputStreamでテキストファイルを直接読み込む人は少なく、BufferedReaderでカプセル化されます.また、FileInputStreamでも文字化けしの問題が発生しますが、この次のInputStreamReaderでお話しします.

4. FileOutputStream


4.1説明
FileOutputStreamはOutputStreamのサブクラスであり、ファイルへの書き込みを実現する.
A file output stream is an output stream for writing data to a File or to a FileDescriptor. Whether or not a file is available or may be created depends upon the underlying platform. Some platforms, in particular, allow a file to be opened for writing by only one FileOutputStream (or other file-writing object) at a time. In such situations the constructors in this class will fail if the file involved is already open.FileOutputStream is meant for writing streams of raw bytes such as image data. For writing streams of characters, consider using FileWriter.
単純翻訳
FileOutputStreamはファイルを書くために使われていますが、これはオペレーティングシステムに依存しており、FileOutputStreamを1つしか操作できないオペレーティングシステムもあります.FileOutputStreamはバイナリを書くためのもので、文字を書く場合はFileWriterを使用します.
4.2コンストラクション関数
FileOutputStream(File file)
Creates a file output stream to write to the file represented by the specified File object.
FileOutputStream(File file, boolean append)
Creates a file output stream to write to the file represented by the specified File object.
FileOutputStream(FileDescriptor fdObj)
Creates a file output stream to write to the specified file descriptor, which represents an existing connection to an actual file in the file system.
FileOutputStream(String name)
Creates a file output stream to write to the file with the specified name.
FileOutputStream(String name, boolean append)
Creates a file output stream to write to the file with the specified name.

以上のように、5つのコンストラクション関数があり、appendがtrueの場合、ファイルを追加書きます.
FileOutputStream fos = new FileOutputStream("d:/123.txt", true);

4.3主な方法
void	close()
Closes this file output stream and releases any system resources associated with this stream.
protected void	finalize()
Cleans up the connection to the file, and ensures that the close method of this file output stream is called when there are no more references to this stream.
FileChannel	getChannel()
Returns the unique FileChannel object associated with this file output stream.
FileDescriptor	getFD()
Returns the file descriptor associated with this stream.
void	write(byte[] b)
Writes b.length bytes from the specified byte array to this file output stream.
void	write(byte[] b, int off, int len)
Writes len bytes from the specified byte array starting at offset off to this file output stream.
void	write(int b)
Writes the specified byte to this file output stream.

主な方法はBufferedWriterと同じで、簡単な使い方です.
	private void test() {
		try {
			FileOutputStream fos = new FileOutputStream("d:/123.txt", true);
			String s = " ";
			fos.write(s.getBytes());
			fos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

注意:ストリームはcloseにします.文字化けしは扱わない.どうして文字化けしを処理しないのですか.これはバイナリを読み取るので、バイナリは符号化の問題がありません.
参考:JavaソースJava Platform Standard Edition 7 Documentation