java字符流的好处_Java中字节流和字符流的必要性是什么?

Java提供了I / O流来读写数据,其中,流表示输入源或输出目标,它可以是文件,I / O设备,其他程序等。

根据他们处理的数据,有两种类型的流-

字节流

它们以字节(8位)为单位处理数据,即字节流类读取/写入8位数据。使用这些可以存储字符,视频,音频,图像等。

InputStream和OutputStream类(抽象)是所有输入/输出流类的超类:用于读取/写入字节流的类。以下是Java提供的字节数组流类-输入流输出流FIleInputStreamFileOutputStream

ByteArrayInputStreamByteArrayOutputStream

ObjectInputStreamObjectOutputStream

PipedInputStreamPipedOutputStream

FilteredInputStreamFilteredOutputStream

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提供的字符数组流类-读者作家缓冲读取器缓冲写入器

CharacterArrayReaderCharacterArrayWriter

字符串阅读器StringWriter

文件阅读器FileWriter

InputStreamReaderInputStreamWriter

文件阅读器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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值