java new file,Java FileInputStream

 2023-11-19 阅读 24 评论 0

摘要:1. Java FileInputStream類 (1. Java FileInputStream Class) Java FileInputStream class is a part of java.io package. Java FileInputStream類是java.io包的一部分。 FileInputStream obtains input bytes from a file in a file system. FileInputStream從文件系統中的

1. Java FileInputStream類 (1. Java FileInputStream Class)

  • Java FileInputStream class is a part of java.io package.

    Java FileInputStream類是java.io包的一部分。
  • FileInputStream obtains input bytes from a file in a file system.

    FileInputStream從文件系統中的文件獲取輸入字節。
  • FileInputStream is used for reading streams of raw bytes such as image data.

    FileInputStream用于讀取原始字節流,例如圖像數據。
  • FileInputStream is a subclass of InputStream class.

    FileInputStream是InputStream類的子類。

2. FileInputStream類層次結構 (2. FileInputStream Class Hierarchy)

3. FileInputStream構造函數 (3. FileInputStream Constructors)

FileInputStream provides many methods for reading bytes from a file and we can create an instance of FileInputStream using below constructors.

FileInputStream提供了許多從文件讀取字節的方法,我們可以使用以下構造函數創建FileInputStream的實例。

  1. FileInputStream(File file): Creates a FileInputStream object by opening a connection to an actual file by using specified file object.

    FileInputStream(File file) :通過使用指定的文件對象打開與實際文件的連接來創建FileInputStream對象。
  2. FileInputStream(FileDescriptor fdObj): Creates a FileInputStream object by using the specified file descriptor fdObj, which represents an existing connection to an actual file in the file system.

    FileInputStream(FileDescriptor fdObj) :通過使用指定的文件描述符fdObj創建FileInputStream對象,該文件描述符表示與文件系統中實際文件的現有連接。
  3. FileInputStream(String name): Creates a FileInputStream object by opening a connection to an actual file named by the specified name which represents path of the file.

    FileInputStream(String name) :通過打開到一個實際文件的連接來創建FileInputStream對象,該文件由指定名稱表示,該名稱代表文件的路徑。

4. FileInputStream方法 (4. FileInputStream Methods)

Let’s have a look at the below methods of FileInputStream class.

讓我們看一下FileInputStream類的以下方法。

  1. available(): This method returns an estimate of the number of remaining bytes that can be read from input stream without blocking by the next invocation of method for this input stream.

    available() :此方法返回可以從輸入流讀取而不會被該輸入流的方法的下一次調用阻塞的剩余字節數的估計值。
  2. close(): This method closes this file input stream and release any system resources associated with the stream. If this stream has an associated channel then channel is closed as well.

    close() :此方法關閉此文件輸入流并釋放與該流關聯的所有系統資源。 如果此流具有關聯的通道,則通道也將關閉。
  3. finalize(): This method ensures that the close() method of this file input stream is called when there are no more reference to it.

    finalize() :此方法確保在沒有更多引用時,調用此文件輸入流的close()方法。
  4. getChannel(): This method returns the unique FileChannel object associated with this file input stream. The initial position of the returned channel will be equal to the number of bytes read from the file and reading bytes from this stream will increment the channel’s position.

    getChannel() :此方法返回與此文件輸入流關聯的唯一FileChannel對象。 返回的通道的初始位置將等于從文件中讀取的字節數,并且從此流中讀取字節將增加通道的位置。
  5. getFD(): This method returns the FileDescriptor object that represents the connection to the actual file in the file system being used by this FileInputStream.

    getFD() :此方法返回FileDescriptor對象,該對象表示與此FileInputStream使用的文件系統中實際文件的連接。
  6. read(): This method reads a byte of data from this input stream and returns the next byte of data or -1 if the end of file is reached.

    read() :此方法從此輸入流讀取一個字節的數據,并返回下一個數據字節;如果到達文件末尾,則返回-1。
  7. read(byte[] b): This method reads byte of data up to the length of specified array(b.length) from this input stream into specified array of bytes and returns the total number of bytes read into the buffer or -1 if the end of file is reached.

    read(byte[] b) :此方法從此輸入流中讀取直到指定數組(b.length)的長度的數據字節到指定的字節數組,并返回讀入緩沖區的字節總數;如果為-1,則返回-1到達文件末尾。
  8. read(byte[] b, int off, int len): This method reads bytes of data up to specified len from this input stream into specified array of bytes. If specified len is not zero, the method blocks until some input are available; otherwise no bytes are read and 0 is returned. It returns number of bytes read into the buffer or -1 if the end of file is reached.

    read(byte[] b, int off, int len) :此方法從此輸入流中將直到指定len的數據字節讀取到指定的字節數組中。 如果指定的len不為零,則該方法將阻塞,直到有一些輸入可用為止;否則,方法將一直阻塞。 否則,不讀取任何字節,并返回0。 它返回讀入緩沖區的字節數;如果到達文件末尾,則返回-1。
  9. skip(long n): This method skips over and discards specified n bytes of data from the input stream and returns the actual number of bytes skipped. It throws an IOException if the specified n is negative.

    skip(long n) :此方法跳過并從輸入流中丟棄指定的n個字節的數據,并返回實際跳過的字節數。 如果指定的n為負數,則拋出IOException。

5. Java FileInputStream示例 (5. Java FileInputStream Examples)

java new file?Let’s look at some example programs for FileInputStream class.

讓我們看一下FileInputStream類的一些示例程序。

5.1)使用FileInputStream讀取文件 (5.1) Read File using FileInputStream)

package com.journaldev.examples;import java.io.File;
import java.io.FileInputStream;/*** Java Read file using FileInputStream* * @author pankaj**/
public class ReadFileUsingFileInputStream {public static void main(String[] args) {File file = null;FileInputStream fileInputStream = null;try {file = new File("D:/data/file.txt");fileInputStream = new FileInputStream(file);System.out.println("Available bytes in file: "+fileInputStream.available());int line;while ((line=fileInputStream.read()) != -1) {System.out.print((char)line);}} catch (Exception e) {e.printStackTrace();}finally {try {if (fileInputStream != null) {fileInputStream.close();}} catch (Exception e2) {e2.printStackTrace();}}}}

Output:

輸出

Available bytes in file: 48
Hello world.
This is a FileInputStream Program.

Note that file.txt is the file used in above program and its content is printed. You can create any other file and run this program by making the required changes.

DataOutputStream。 請注意, file.txt是上述程序中使用的文件,其內容已打印出來。 您可以創建任何其他文件并通過進行所需的更改來運行該程序。

Java 7 provides try with resource which is a try statement that declares one or more resource. A resource is an object that must be closed after the program is finished with it. The try with resource statement ensures that each resource is closed at the end of the statement.

Java 7提供帶資源的try,它是聲明一個或多個資源的try語句。 資源是程序完成后必須關閉的對象。 try with resource語句可確保在語句末尾關閉每個資源。

Let’s have a look at the below example program using try with resources.

讓我們看一下下面的示例程序,它使用try資源。

package com.journaldev.examples;import java.io.File;
import java.io.FileInputStream;/*** Java Read file using FileInputStream with Try with Resource* * @author pankaj**/
public class FileInputStreamTryWithResource {public static void main(String[] args) {File file = new File("D:/data/file.txt");try (FileInputStream fileInputStream = new FileInputStream(file)){System.out.println("Available bytes in file: "+fileInputStream.available());int line;while ((line=fileInputStream.read()) != -1) {System.out.print((char)line);}} catch (Exception e) {e.printStackTrace();}}}

java的input,It will produce the same result as the earlier program. Also check java read text file for more about how to read text file in java.

它將產生與早期程序相同的結果。 還要檢查Java讀取文本文件,以獲取有關如何在Java中讀取文本文件的更多信息。

5.2)finalize() (5.2) finalize())

FileInputStream finalize() method ensures that the close() method of this file input stream is called when there are no more reference to it.

FileInputStream finalize()方法可確保在沒有更多引用時調用此文件輸入流的close()方法。

If we try to access FileInputStream after calling finalize(), we will get an exception.

FileReader、 如果在調用finalize()之后嘗試訪問FileInputStream,我們將獲得一個異常 。

package com.journaldev.examples;import java.io.FileInputStream;
import java.io.FileNotFoundException;/*** Java FileInputStream Finalize method example* * @author pankaj**/
public class FileInputStreamFinalizeExample extends FileInputStream{public FileInputStreamFinalizeExample(String name) throws FileNotFoundException {super(name);}public static void main(String[] args) {FileInputStreamFinalizeExample file = null;try {file = new FileInputStreamFinalizeExample("D:/data/file.txt"); System.out.println("Available bytes in the file: "+file.available());int line;while ((line=file.read()) != -1) {System.out.print((char)line);}//calling finalize methodfile.finalize();System.out.println("\n");System.out.println("------After finalize called--------");System.out.println(file.available());} catch (Exception e) {e.printStackTrace();}finally {try {if (file != null) {file.close();}} catch (Exception e2) {e2.printStackTrace();}}}}

The output of the above program is below:

上面程序的輸出如下:

Available bytes in the file: 48
Hello world.
This is a FileInputStream Program.------After finalize called--------
java.io.IOException: Stream Closedat java.io.FileInputStream.available(Native Method)at com.journaldev.examples.FileInputStreamFinalizeExample.main(FileInputStreamFinalizeExample.java:31)

5.3)getFD() (5.3) getFD())

FileInputStream getFD() returns the FileDescriptor object that represents the connection to the actual file in the file system being used by this FileInputStream. Let’s have look at the below example program.

FileInputStream getFD()返回FileDescriptor對象,該對象表示與此FileInputStream使用的文件系統中實際文件的連接。 讓我們看下面的示例程序。

package com.journaldev.examples;import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;/*** Java FileInputStream FileDescriptor Example* * @author pankaj**/
public class FileInputStreamFileDescripterExample {public static void main(String[] args) {File file = new File("D:/data/file.txt");try (FileInputStream fileInputStream = new FileInputStream(file)){FileDescriptor fileDescriptor = fileInputStream.getFD();boolean valid = fileDescriptor.valid();System.out.println("Valid file: "+valid);} catch (Exception e) {e.printStackTrace();}}}

java fileutils、Output of the above program is:

上面程序的輸出是:

Valid file: true

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

This method reads bytes of data up to specified length from this input stream into a specified array of bytes. If specified length is not zero, the method blocks until some input is available; otherwise, no bytes are read and 0 is returned. It returns the number of bytes read into the buffer or -1 if the end of file is reached.

此方法從此輸入流中讀取指定長度的數據字節到指定的字節數組中。 如果指定的長度不為零,則該方法將阻塞,直到有可用的輸入為止;否則,該方法將停止。 否則,不讀取任何字節,并返回0。 它返回讀入緩沖區的字節數;如果到達文件末尾,則返回-1。

package com.journaldev.examples;import java.io.FileInputStream;/*** Java Read file using read(byte[] b, int off, int len) method* * @author pankaj**/
public class FileInputStreamRead {public static void main(String[] args) {try (FileInputStream fileInputStream = new FileInputStream("D:/data/file.txt")) {byte[] b = new byte[10];int i = fileInputStream.read(b, 0, 8);System.out.println("Available bytes in file: " + fileInputStream.available());System.out.println("Number of bytes in read from file: " + i);for (byte bs : b) {char c = (char) bs;if (bs == 0) {c = '-';}System.out.print(c);}} catch (Exception e) {e.printStackTrace();}}}

Output:

FileInputStream, 輸出

Available bytes in file: 40
Number of bytes in read from file: 8
Hello wo--

5.5)跳過(長n) (5.5) skip(long n))

FileInputStream skip(long n) method skips over and discards specified n bytes of data from the input stream and returns the actual number of bytes skipped. It throws an IOException if the specified n is negative.

FileInputStream skip(long n)方法跳過并丟棄輸入流中指定的n個字節的數據,并返回實際跳過的字節數。 如果指定的n為負數,則拋出IOException。

package com.journaldev.examples;import java.io.FileInputStream;/*** Java Read file with skip(long n) method example* * @author pankaj**/
public class FileInputStreamSkip {public static void main(String[] args) {try (FileInputStream fileInputStream = new FileInputStream("D:/data/file.txt")) {System.out.println("Available bytes in the file: " + fileInputStream.available());int line;//skip 2 bytesfileInputStream.skip(2);System.out.println("Available bytes in the file after skip: " + fileInputStream.available());while ((line=fileInputStream.read()) != -1) {System.out.print((char)line);}} catch (Exception e) {e.printStackTrace();}}}

The output of the above program is:

上面程序的輸出是:

Available bytes in the file: 12
Available bytes in the file after skip: 10
llo world.

5.6)getChannel() (5.6) getChannel())

DataInputStream、This method returns the unique FileChannel object associated with this file input stream. The initial position of the returned channel will be equal to the number of bytes read from the file and reading bytes from this stream will increment the channel’s position.

此方法返回與此文件輸入流關聯的唯一FileChannel對象。 返回的通道的初始位置將等于從文件中讀取的字節數,并且從此流中讀取字節將增加通道的位置。

package com.journaldev.examples;import java.io.FileInputStream;
import java.nio.channels.FileChannel;/*** Java Read file with getChannel method example* * @author pankaj**/
public class FileInputStreamChannel {public static void main(String[] args) {FileInputStream fileInputStream = null;FileChannel fileChannel = null;try {fileInputStream = new FileInputStream("D:/data/file.txt");System.out.println("Available bytes in file: " + fileInputStream.available());int line;while ((line=fileInputStream.read()) != -1) {fileChannel = fileInputStream.getChannel();System.out.print("No of bytes read: "+fileChannel.position());System.out.println("; Char read: "+(char)line);}} catch (Exception e) {e.printStackTrace();}finally {try {if (fileInputStream != null) {fileInputStream.close();}if (fileChannel != null) {fileChannel.close();}} catch (Exception e2) {e2.printStackTrace();}}}}

Output:

輸出:

Available bytes in file: 12
No of bytes read: 1; Char read: H
No of bytes read: 2; Char read: e
No of bytes read: 3; Char read: l
No of bytes read: 4; Char read: l
No of bytes read: 5; Char read: o
No of bytes read: 6; Char read:  
No of bytes read: 7; Char read: w
No of bytes read: 8; Char read: o
No of bytes read: 9; Char read: r
No of bytes read: 10; Char read: l
No of bytes read: 11; Char read: d
No of bytes read: 12; Char read: .

That’s all for Java FileInputStream, I hope nothing important got missed here.

Java FileInputStream就這些了,我希望這里沒有重要的事情。

Reference: API Doc

參考: API文檔

翻譯自: https://www.journaldev.com/19187/java-fileinputstream

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/2/183204.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息