Java 中的字节流
这些数据以字节(8 位)形式处理,即字节流类读/写 8 位数据。使用这些数据,你可以存储字符、视频、音频、图像等。
InputStream 和 OutputStream 类(抽象)是所有输入/输出流类的超类:用于读/写字节流的类。以下是 Java 提供的字节数组流类 −
InputStream | OutputStream |
---|---|
FIleInputStream | FileOutputStream |
ByteArrayInputStream | ByteArrayOutputStream |
ObjectInputStream | ObjectOutputStream |
PipedInputStream | PipedOutputStream |
FilteredInputStream | FilteredOutputStream |
BufferedInputStream | BufferedOutputStream |
DataInputStream | DataOutputStream |
示例
以下 Java 程序使用 FileInputStream 从特定文件中读取数据,并使用 FileOutputStream 将其写入另一个文件。
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class IOStreamsExample { public static void main(String args[]) throws IOException { //Creating FileInputStream object File file = new File("D:/myFile.txt"); FileInputStream fis = new FileInputStream(file); byte bytes[] = new byte[(int) file.length()]; //Reading data from the file fis.read(bytes); //Writing data to another file File out = new File("D:/CopyOfmyFile.txt"); FileOutputStream outputStream = new FileOutputStream(out); //Writing data to the file outputStream.write(bytes); outputStream.flush(); System.out.println("Data successfully written in the specified file"); } }
输出
Data successfully written in the specified file
广告