Java架构师之旅(三十三 基础IO流)

夜光序言:

我的兴趣爱好可分为静态和动态两种,静态就是睡觉,动态就是翻身…

正文:

 

字符流:只可以处理纯文本,比如说.txt和.html

节点流:Reader FileReader

        Writer FileWriter

纯文本读取

  • 建立联系
  • 选择流
  • 读取
  • 关闭

上图我们可以通过一行代码来控制显示的规整程度,1024

package com.Genius.byteIO;

 

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.IOException;

import java.io.Reader;

 

/*夜光:纯文本读取*/

public class Demo03 {

 

public static void main(String[] args) {

// 1、创建源

File src = new File("E:/Genius/parent/test/Demo03.txt");

        // 2、选择流

Reader reader = null;

try {

reader = new FileReader(src);

// 3、这里我们写一点东西

char[] flush = new char[1024];

int len = 0;

while(-1!=(len=reader.read(flush))){

//字符数组转换成字符串

String str = new String(flush,0,len);

System.out.println(str);

}

 

 

 

} catch (FileNotFoundException e) {

e.printStackTrace();

System.out.println("源文件不存在~~");

} catch (IOException e) {

e.printStackTrace();

System.out.println("文件读取失败~~");

}finally {

if(null!=reader){

try {

reader.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

 

}

2、纯文本写出

Write(字符串)

append(字符串|数组)

package com.Genius.byteIO;

 

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileWriter;

import java.io.IOException;

import java.io.Writer;

 

//夜光:文件的写出

public class Demo04 {

   public static void main(String[] args) {

   //创建源

   File dest = new File("E:/Genius/parent/test/Demo04.txt");

   //选择流

   Writer wr = null;

   try {

wr = new FileWriter(dest);

//夜光:之后我们写出

String msg = "夜光:看得到呢……在黑暗中,闪着光芒……简直就像是,星星一样……在大陆的,房屋旁边……每晚,都会一个人,仰望的……夜空中的星星……就像……你的剑的……光辉一样……";

wr.write(msg);

wr.append("天空之下");

 

wr.flush();

} catch (FileNotFoundException e) {

 

e.printStackTrace();

} catch (IOException e) {

 

e.printStackTrace();

}finally {

if(null!=wr){

try {

wr.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

   

}

}

猜你喜欢

转载自blog.csdn.net/weixin_41987706/article/details/86569406
今日推荐