栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java io流概述1---字节流与字符流

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java io流概述1---字节流与字符流

io流概述:

io:io是input与output的缩写

流:数据在设备之间传输称为流

io流主要用于文件的复制,上传,下载

分类:

输入流与输出流

按照数据类型:

字节流(通过windows记事本打开读不懂的)

字符流(通过windows记事本打开读的懂的)

字节流:

字节输出流声明:

FileOutputStream fos1 = new FileOutputStream("fos1.txt");
FileOutputStream fos2 = new FileOutputStream(new File("fos2.txt"));

可以使用这两种方式

写数据的三种方式:

第一种方式:
fos.write(97);
fos.write(98);
fos.write(99);
第二种方式:
byte[] bys = {97,98,99,100,101,102};
fos.write(bys);
String s = "abcde";
byte[] bys = s.getBytes();
fos.write(bys);

通过String的getBytes()方法转换为byte[]类型调用第二种方法输出

第三种方式:
String s = "abcde";
byte[] bys = s.getBytes();
fos.write(bys,1,3);

从索引1开始往后写三个字节

小问题:怎样实现换行:

windows:/r/n

linux:/n

mac:/r

追加写入:把第二个参数设置为true

FileOutputStream fos = new FileOutputStream("fos.txt",true);

 上图为构造方法

字节输入流

字节流读数据,每次读一个字节:

// 创建一个新的对象
FileInputStream fis = new FileInputStream("fos.txt");
// 控制台输出一个读入的字节
System.out.println((char)fis.read());
// 释放资源
fis.close();
FileInputStream fis = new FileInputStream("fos.txt");

System.out.println((char)fis.read());
System.out.println((char)fis.read());

fis.close();

此时可以读到第二个数据

当读到-1时,文本数据被读完

可使用循环

int by = fis.read();
while(by != -1){
    System.out.print((char) by);
    by = fis.read();
}

也可以优化为下面的代码:

int by;
while((by=fis.read()) != -1){
    System.out.print((char) by);
}

字节输入输出流实现文件的复制:

FileInputStream fis = new FileInputStream("fos.txt");
FileOutputStream fos = new FileOutputStream("fos_fb.txt");
int by;
while((by=fis.read()) != -1){
    fos.write(by);
}
fis.close();
fos.close();

避免乱码问题引入:

字符流

字符流=字节流+编码表

中文的识别是靠第一个数字为负数

OutputStreamWriter ows = new OutputStreamWriter(new FileOutputStream("fos.txt",true));
String s = "中国";
ows.write(s);
ows.flush();
ows.close();

使用字符流可以避免中文的乱码问题,flush()方法可以实现刷新。

如果忘掉刷新流,close()方法也可以先刷新再关闭

字符流写数据的五种方式:

写入单个字符:

OutputStreamWriter ows = new OutputStreamWriter(new FileOutputStream("fos.txt",true));
String s = "Hello world!";
ows.write(s);
ows.flush();
ows.close();

上述写入字符串中国也是一种方法。

写入char[ ]:

char[] chars = {'a','b','c'};
ows.write(chars);

写入char[] cbuf, int off, int len

char[] chars = {'a','b','c'};
ows.write(chars,0,chars.length);

写入String str, int off, int len:

String s = "Hello world!";
ows.write(s,0,s.length());

字符流读数据:

int len;
char[] chars = new char[1024];
while((len=isr.read(chars)) != -1){
    System.out.print(new String(chars,0,len));
}

每次读字节数组的示例

另外还有缓冲流,速度会更快,方法类似

字符缓冲流特有功能:readLine() != null

读完每行之后需要换行:

String line;
while((line=br.readLine()) != null){
    bw.write(line);
    bw.newLine();
    bw.flush();
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/820378.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号