Java 中IO流字符流详解及实例

2025-05-29 0 90

JavaIO流 字符流

  java的文本(char)是16位无符号整数,是字符的unicode编码(双字节编码)。

  文件是byte byte byte … 的数据序列。

  文本文件是文本(char)序列按照某种编码方案(uft-8、utf-16be、gbk)序列化为byte的存储结果。

字符流(Reader、Writer)–>操作的是文本、文本文件

  1.字符的处理,一次处理一个字符

  2.字符的底层仍然是基本的字节序列

  3.字符流的基本实现:

  InputStreamReader是字节流通向字符流的桥梁:它使用指定的 charset 读取字节并将其解码为字符。

  OutputStreamWriter字符流通向字节流的桥梁:可使用指定的 charset 将要写入流中的字符编码成字节。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25
public class ISReaderAndOSWriter {

public static void main(String[] args) throws IOException {

FileInputStream in = new FileInputStream("F:\\\\javaio\\\\java.txt");

FileOutputStream out = new FileOutputStream("F:\\\\javaio\\\\java1.txt");

InputStreamReader isr = new InputStreamReader(in, "gbk");

OutputStreamWriter osw = new OutputStreamWriter(out, "gbk");

int c;

// while ((c = isr.read()) != -1) {

// System.out.print((char)c);

// }

char[] buf = new char[8 * 1024];

while ((c = isr.read(buf, 0, buf.length)) != -1) {

String s = new String(buf, 0, c);

//System.out.println(s);

osw.write(s);

}

isr.close();

osw.close();

}

}

  4.文件读写流,FileReader和FileWriter,读取字符文件和写入字符文件的便捷类。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17
public class FileReaderAndFileWriter {

public static void main(String[] args) throws Exception {

FileReader fr = new FileReader("F:\\\\javaio\\\\javautf.txt");

FileWriter fw = new FileWriter("F:\\\\javaio\\\\javautf1.txt");

//FileWriter fw = new FileWriter("F:\\\\javaio\\\\javautf1.txt", true);//向指定文件中追加内容

char[] buf = new char[1 * 1024];

int c;

while ((c = fr.read(buf, 0, buf.length)) != -1) {

System.out.println(c);

fw.write(buf, 0, c);

fw.flush();

}

fr.close();

fw.close();

}

}

  5.字符流的过滤器

  BufferedReader,一次读一行

  BufferedWriter/PrintWriter,一次写一行

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21
public class BufRAndBufWOrPrintW {

public static void main(String[] args) throws Exception {

BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("F:\\\\javaio\\\\javautf.txt")));

//BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("F:\\\\javaio\\\\javautf2.txt")));

PrintWriter pw = new PrintWriter("F:\\\\javaio\\\\javautf3.txt");

String s;

while ((s = br.readLine()) != null) {

//一次读一行,不能识别换行符

//bw.write(s);

//bw.newLine();//写入一个行分隔符

//bw.flush();

pw.println(s);//通过写入行分隔符字符串终止当前行

pw.flush();

}

br.close();

//bw.close();

pw.close();

}

}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

原文链接:http://www.cnblogs.com/tianxintian22/p/6838545.html

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Java 中IO流字符流详解及实例 https://www.kuaiidc.com/116558.html

相关文章

发表评论
暂无评论