Java提供了I / O流来读写数据,其中,流表示输入源或输出目标,它可以是文件,I / O设备,其他程序等。
根据他们处理的数据,有两种类型的流-
它们以字节(8位)为单位处理数据,即字节流类读取/写入8位数据。使用这些可以存储字符,视频,音频,图像等。
InputStream和OutputStream类(抽象)是所有输入/输出流类的超类:用于读取/写入字节流的类。以下是Java提供的字节数组流类-
输入流 | 输出流 |
---|---|
FIleInputStream | FileOutputStream |
ByteArrayInputStream | ByteArrayOutputStream |
ObjectInputStream | ObjectOutputStream |
PipedInputStream | PipedOutputStream |
FilteredInputStream | FilteredOutputStream |
BufferedInputStream | 缓冲输出流 |
数据输入流 | 数据输出流 |
以下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 { //创建FileInputStream对象 File file = new File("D:/myFile.txt"); FileInputStream fis = new FileInputStream(file); byte bytes[] = new byte[(int) file.length()]; //从文件读取数据 fis.read(bytes); //将数据写入另一个文件 File out = new File("D:/CopyOfmyFile.txt"); FileOutputStream outputStream = new FileOutputStream(out); //将数据写入文件 outputStream.write(bytes); outputStream.flush(); System.out.println("Data successfully written in the specified file"); } }
输出结果
Data successfully written in the specified file
字符流-这些字符流以16位Unicode处理数据。使用这些只能读取和写入文本数据。
Reader和Writer类(抽象类)是所有字符流类的超类:用于读取/写入字符流的类。以下是Java提供的字符数组流类-
读者 | 作家 |
---|---|
缓冲读取器 | 缓冲写入器 |
CharacterArrayReader | CharacterArrayWriter |
字符串阅读器 | StringWriter |
文件阅读器 | FileWriter |
InputStreamReader | InputStreamWriter |
文件阅读器 | FileWriter |
随后的Java程序使用FileReader从特定文件读取数据,然后使用FileWriter将数据写入另一个文件。
import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class IOStreamsExample { public static void main(String args[]) throws IOException { //创建FileReader对象 File file = new File("D:/myFile.txt"); FileReader reader = new FileReader(file); char chars[] = new char[(int) file.length()]; //从文件读取数据 reader.read(chars); //将数据写入另一个文件 File out = new File("D:/CopyOfmyFile.txt"); FileWriter writer = new FileWriter(out); //将数据写入文件 writer.write(chars); writer.flush(); System.out.println("Data successfully written in the specified file"); } }
输出结果
Data successfully written in the specified file