首页 > 图灵资讯 > 技术篇>正文

java中的字符流可以读取word文件内容吗 java 字符串流

2023-05-16 09:20:30

一、字符流

字符流概述:字节流可以在操作过程中操作所有数据,操作文件中有中文字符,需要处理中文字符

二、字符编码表

文字——>(数字):编码。"abc".getBytes() byte[]数字——>(文字):解码。byte[] b = {97, 98, 99} new String(b)

三、字符输入流Readerfilereder类型

这种结构方法假设默认字符编码和默认字节缓冲区大小合适;用于操作文件的字符输入流(简单流)

用字节流读写中文字符
public class CharStreamDemo {public static void main(String[] args) throws IOException {// 中文writeCNText()写在文件中;// 读取文件中的中文,读取数字,与字符编码表相关的readCNText();}public static void readCNText() throws IOException {InputStream is = new FileInputStream("e:/file.txt");int ch = 0;while((ch = is.read()) != -1){System.out.println(ch);}is.close();}public static void writeCNText() throws IOException {OutputStream os = new FileOutputStream("e:/file.txt");os.write(欢迎Java~~”.getBytes());os.close();}}
使用字符输出流读取字符

字符输出流(简单流)用于操作文件

public class CharStreamDemo {public static void main(String[] args) throws IOException {// 中文writeCNText()写在文件中;// 读取文件中的中文readCNText();}public static void readCNText() throws IOException {Reader reader = new FileReader("e:/file.txt");int ch = 0;while((ch = reader.read()) != -1){// 输入字符对应的编码System.out.print(ch + " = ");// Systemem输入字符本身.out.println((char) ch);}reader.close();}public static void writeCNText() throws IOException {OutputStream os = new FileOutputStream("e:/file.txt");os.write(欢迎Java~~”.getBytes());os.close();}}
四、字符输入流WriterfileWriter

将字符写入文件中,先刷新流量,然后关闭流量

flush() & close() 的区别

flush():将流中缓冲区缓冲的数据刷新到目的地,刷新后,流可以继续使用close():关闭资源,但缓冲区的数据会在关闭前刷新到目的地,否则数据会丢失,然后关闭流量。流量不能使用。如果你写了很多数据,一定要边写边刷新。最后一次不能刷新,Close可以刷新关闭。

public class FileWriterDemo {public static void main(String[] args) throws IOException {Writer writer = new FileWriter("e:/text.txt");writer.write("你好,谢谢,再见”);/* * flush() & close() * 区别: * flush():将流中缓冲区缓冲数据刷新到目的地,刷新后, * 流也可以继续使用 * close():关闭资源,但缓冲区的数据将在关闭前刷新到目的地, *           否则数据丢失,然后关闭流量。不能使用流量。不能使用流量。 * 若写入数据较多,必须边写边刷新,最后一次不能刷新, * 刷新并关闭close。 */writer.flush();writer.close();}}
上一篇 全方位深入解析最新版SpringBoot源码
下一篇 KVO/KVC 实现机理分析

文章素材均来源于网络,如有侵权,请联系管理员删除。