Java-I/O学习(2)

Java-I/O学习(2)

InputStream

InputStream是Java IO中所有输入流的基类

方法列表:

读取操作:

返回类型方法具体描述
abstract intread()Reads the next byte of data from the input stream.
intread​(byte[] b)Reads some number of bytes from the input stream and stores them into the buffer array b.
intread​(byte[] b, int off, int len)Reads up to len bytes of data from the input stream into an array of bytes.
byte[]readAllBytes()Reads all remaining bytes from the input stream.
intreadNBytes​(byte[] b, int off, int len)Reads the requested number of bytes from the input stream into the given byte array.

其余操作:

返回类型方法具体描述
intavailable()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.
voidclose()Closes this input stream and releases any system resources associated with the stream.
voidmark​(int readlimit)Marks the current position in this input stream.
booleanmarkSupported()Tests if this input stream supports the mark and reset methods.
voidreset()Repositions this stream to the position at the time the mark method was last called on this input stream.
longskip​(long n)Skips over and discards n bytes of data from this input stream.
longtransferTo​(OutputStream out)Reads all bytes from this input stream and writes the bytes to the given output stream in the order that they are read.

使用


public static void main(String[] args) throws IOException {

        InputStream inputstream = new FileInputStream("E:\\learn-java\\Learning-Java\\MyNotes\\better_write\\Java_IO\\bb.txt");

        int data = inputstream.read();
        while(data != -1) {
            //do something with data...
//            doSomethingWithData(data);

            System.out.println(data);
            data = inputstream.read();
        }
        inputstream.close();

    }
    //这个例子中创建了一个FileInputStream实例。FileInputStream是InputStream的子类所以它可以InputStream类型的变量。

Java7开始,你可以用try-with-resources去确保InputStream在使用后可以关闭


try( InputStream inputstream = new FileInputStream("file.txt") ) {

    int data = inputstream.read();
    while(data != -1){
        System.out.print((char) data);
        data = inputstream.read();
    }
}

只要线程已经执行出try代码块,inputstream就会被关闭。

read()

InputStream的read()方法返回一个int类型的值,这个值是每次读取的字节的值。下面是一个相关的例子:


int data = inputstream.read();

如果read()方法返回 -1,就说明流到已经全部读取完毕。这里的 -1 是int类型的,不是byte或short

read(byte[])

InputStream有两个read()方法,参数是一个字节数组

每次读取一个字节数组显然要比每次读取一个字节要快的多,所以只要有可能,你可以使用这类的方法来替代read()方法。

read(byte[])方法会读取所有数据到数组中。它会返回一个int值,来告诉实际读取的字节数。万一实际读取的字节数要比提供的字节少,那么字节数组的其余部分将包含与读取开始之前所做的相同的数据。要记住去检查返回的int值,看实际取得的字节数有多少。
read(byte[], int offset, int length)方法也是读数组到数组中,但是可以根据参数来规定开始的偏移量和一共读取多少长度。返回值和read(byte[])方法的含义相同。

两个方法相同的地方都是如果返回值是 -1 ,代表读取结束。


 public static void main(String[] args) throws IOException {

        InputStream in = new FileInputStream("E:\\learn-java\\Learning-Java\\MyNotes\\better_write\\Java_IO\\c.txt");

        byte[] bytes = new byte[1024];

        int data = in.read(bytes);

        while (data != -1) {
//            System.out.println(data);
            data = in.read(bytes);
        }
        
    }
mark()和reset()

InputStream类中有两个方法mark()和reset(),但是它的子类不一定有支持(或者说子类有没有重写此方法)。

如果一个InputStream的子类支持这两个方法,子类会重写markSupported()方法并返回 true。相反的,如果返回false,则子类不支持这两个方法。

mark()方法在InputStream设置一个内部的标记,标记在流中哪个数据到目前为止已经被读取。使用InputStream的代码,可以根据这个标记位来继续读取数据。

在读取流的过程汇总,如果想退回到标记的那点上,可以调用reset()方法。然后InputStream退回到标记位上,开始从这个位置开始返回数据。这当然会导致多次返回一些数据

当实现一个解析器时,会经常用到这两个方法。解析器读取一个InputStream时会提前读,如果解析器没有找到它想要的,他可能需要回退并且将已读数据和其他的数据进行匹配。

OutputStream

Java IO API中,OutputStream是所有输出流的基类。子类包括BufferedOutputStream,FileOutputStream等等

OutputStream经常用来连接到数据目的地,比如文件,网络连接,管道等等。OutputStream将所有数据的数据写入目的地后即结束。

方法列表:

写入操作:

返回类型方法具体描述
voidwrite​(byte[] b)Writes b.length bytes from the specified byte array to this output stream.
voidwrite​(byte[] b, int off, int len)Writes len bytes from the specified byte array starting at offset off to this output stream.
abstract voidwrite​(int b)Writes the specified byte to this output stream

其余:

返回类型方法具体描述
voidclose()Closes this output stream and releases any system resources associated with this stream.
voidflush()Flushes this output stream and forces any buffered output bytes to be written out.

写入

write(int b)

方法用来向流中写入单个字节。参数为int类型,也就是准备写出的数据。只有int值的第一个字节会被写入。其余的都会被忽略

write(byte[])

OutputStream也有write(byte[] bytes)方法和write(byte[] bytes, int offset, int length)方法,这两个都是写入一个或部分数组内的字节到OutputStream。

write(byte[] bytes)方法是将数组内所有数据写入到OutputStream。而write(byte[] bytes, int offset, int length)可以规定从哪里开始写,一共写多少长度的数据


 public static void main(String[] args) throws IOException {

        OutputStream out = new FileOutputStream("E:\\learn-java\\Learning-Java\\MyNotes\\better_write\\Java_IO\\d.txt");

        String[] strings = {"djdjdjs","5645","sjdjjd"};

        for (String s : strings) {

            out.write(s.getBytes());
        }

        out.close();

    }
flush()

OutputStream的flush()方法刷新所有已经写入OutputStream的数据到数据目的地。例如,如果OutputStream是一个FileOutputStream的话,写入FileOutputStream的的字节可能并没有全部被写入到磁盘,他们可能在内存缓冲区里,虽然你的Java代码已经将数据写入到FileOutputStream,但是通过flush()方法,你可以确保数据都已经写到磁盘(网络连接或其他的数据目标地)

FileInputStream

使用FileInputStream可以以字节流的形式来读取文件内容。FileInputStream是InputStream的子类,所以你可以使用FileInputStream像InputStream一样。

方法列表:

构造函数:

构造方法具体描述
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.

read方法:

返回类型方法具体描述
intread()Reads a byte of data from this input stream.
intread​(byte[] b)Reads up to b.length bytes of data from this input stream into an array of bytes.
intread​(byte[] b, int off, int len)Reads up to len bytes of data from this input stream into an array of bytes.

其余方法:

返回类型方法具体描述
intavailable()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.
voidclose()Closes this file input stream and releases any system resources associated with the stream.
protected voidfinalize()Deprecated, for removal: This API element is subject to removal in a future version.The finalize method has been deprecated and will be removed.
FileChannelgetChannel()Returns the unique FileChannel object associated with this file input stream.
FileDescriptorgetFD()Returns the FileDescriptor object that represents the connection to the actual file in the file system being used by this FileInputStream.
longskip​(long n)Skips over and discards n bytes of data from the input stream.
构造函数

第一个构造方法有一个String类型的参数。这个参数是指你想要读取的文件路径


/**
* If the named file does not exist, is a directory rather than a regular
* file, or for some other reason cannot be opened for reading then a
* <code>FileNotFoundException</code> is thrown.
*/
FileInputStream(String name)

第二个构造方式是提供一个File类型的参数。这个参数你可以传入你想要读取的文件:


FileInputStream(File file)
读取
read()

FileInputStream的read()方法会返回一个int值,它是读取的字节。如果返回 -1,那么说明已经读取完毕。-1是int值,而不是一个byte值,这里可是不一样的。这个方法和InputStream中的read()使用是一样的

read(byte b[])与read(byte b[], int off, int len)

读取若干字节并填充到byte[]数组,返回读取的字节数,-1时表示读取完毕


    public static void main(String[] args) throws IOException {

        FileInputStream in = new FileInputStream("E:\\learn-java\\Learning-Java\\MyNotes\\better_write\\Java_IO\\c.txt");

        byte[] bytes = new byte[1024];

        int data = in.read(bytes);

        while (data != -1) {
//            System.out.println(data);
            data = in.read(bytes);
        }

        in.close();

    }

FileOutputStream

FileOutputStream可以以流的形式写出一个文件。他是OutputStream的子类。

方法列表:

构造函数:

构造方法具体描述
FileOutputStream​(File file)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​(File file, boolean append)Creates a file output stream to write to the file represented by the specified File object.
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.

write​方法:

返回类型方法具体描述
voidwrite​(byte[] b)Writes b.length bytes from the specified byte array to this file output stream.
voidwrite​(byte[] b, int off, int len)Writes len bytes from the specified byte array starting at offset off to this file output stream.
voidwrite​(int b)Writes the specified byte to this file output stream.

其余方法:

返回类型方法具体描述
voidclose()Closes this file output stream and releases any system resources associated with this stream.
protected voidfinalize()Deprecated, for removal: This API element is subject to removal in a future version.The finalize method has been deprecated and will be removed.
FileChannelgetChannel()Returns the unique FileChannel object associated with this file output stream.
FileDescriptorgetFD()Returns the file descriptor associated with this stream.
构造函数

第一个构造方法需要传入一个String类型的参数,即你要写出数据的目标文件路径:

/**
* If the file exists but is a directory rather than a regular file, does
* not exist but cannot be created, or cannot be opened for any other
* reason then a <code>FileNotFoundException</code> is thrown.
*/
FileOutputStream(String name)

第二个构造方法为传入一个File类型的参数,它指向的是系统上的一个文件:

FileOutputStream(File file)


如果构造方法只传入一个参数也就是文件全名,那么就会覆盖已存在的文件,所以还有两个带两个参数的构造方法,一个参数是文件名(或File),还有一个参数为boolean类型,它表明了你是想覆盖还是想增量写入

FileOutputStream(String name, boolean append)


/**

* Creates a file output stream to write to the file represented by
* the specified <code>File</code> object. If the second argument is
* <code>true</code>, then bytes will be written to the end of the file
* rather than the beginning. A new <code>FileDescriptor</code> object is
* created to represent this file connection.
*/

FileOutputStream(File file, boolean append)


OutputStream output = new FileOutputStream("c:\\data\\output-text.txt", true); //增量写入文件

OutputStream output = new FileOutputStream("c:\\data\\output-text.txt", false); //覆盖文件

写入

   public static void main(String[] args) throws IOException {

        FileOutputStream out = new FileOutputStream("E:\\learn-java\\Learning-Java\\MyNotes\\better_write\\Java_IO\\d.txt",true);

        String[] strings =
                {
                  "abcdefg",
                  "123456789",
                  "a124sjd"
                };

        for (String s : strings) {

            out.write("\n".getBytes());
            out.write(s.getBytes());
            out.write("\n".getBytes());

        }

        out.close();
    }

flush()
当你把数据写入FileOutputStream,数据有可能缓存在计算机的内存中,会晚一些写入磁盘。例如每当有“X”数量的数据需要写入时,或者FileOutputStream流已经关闭。
如果你想确定在流未关闭并且所有的数据已经写入磁盘,那么你可以调用flush()方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值