字节流和字符流的相互转换


/*

 * 读取键盘输入

 * read()是一个阻塞式方法

 * system.in是标准输入默认设备是键盘

 * system.out是标准是输出默认设备是控制台

 * \r 对应ASC码的数字是13

 * \n 对应ASC码的数字是10

 * 在命令模式下停下程序的方法:ctrl+c

 * 需求:

 * 从键盘循环输入数据,输入一行后打印,当输入为OVER时,结束输入

 * */

import java.io.*;

 

public class ReaderIn {

 

/**

 * @param args

 */

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

InputStream in = System.in;

System.out.println("请输入信息:");

/*

 * int num =in.read(); System.out.println(num);

 */

StringBuilder str = new StringBuilder();

int b = 0;

while (true) {

b = in.read();

if (b == '\r')

continue;

if (b == '\n') {

String s=str.toString();

if(s.equals("over"))

break;

System.out.println(s.toUpperCase());

str.delete(0, str.length());//清空缓冲区

}else{

str.append((char)b);

}

 

}

 

}

}

 

以字符流的形式去操作键盘输入的字节流

package itheima.stream;

 

import java.io.*;

 

public class InputStreamReaderDemo {

 

/**

 * readLine是BufferedReader中的方法 而键盘输入的read方法是字节流InputStream的方法

 * 能不能把字节流转换成字符流,然后用高效readline方法去读取键盘的出入呢

 */

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

// 从键盘输入

InputStream in = System.in;

// 字节流转换成字符流

InputStreamReader ir = new InputStreamReader(in);

// 然后用字符流的缓冲区 操作由字节流转换成的字符流的ir

BufferedReader buff = new BufferedReader(ir);

String line = null;

while ((line = buff.readLine()) != null) {

System.out.println(line);

}

 

}

 

}

 

 

 

 

 

 

字符流转换成字节流输出

 

/**

 * 字符流转换成字节流输出

 * 

 * 

 * */

import java.io.*;

 

 

public class OutputStreamWriterDemo {

 

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

// 从键盘输入

InputStream in = System.in;

// 字节流转换成字符流

InputStreamReader ir = new InputStreamReader(in);

// 然后用字符流的缓冲区 操作由字节流转换成的字符流的ir

BufferedReader buff = new BufferedReader(ir);

 

// * 字符流转换成字节流输出

OutputStream out = System.out;

// 转换流

OutputStreamWriter oi = new OutputStreamWriter(out);//

// 主要是为了能用newLine;跨平台换行

BufferedWriter buffw = new BufferedWriter(oi);

 

String line = null;

while ((line = buff.readLine()) != null) {

buffw.write(line);

buffw.newLine();

buffw.flush();

}

buff.close();

buffw.close();

}

 

}



  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值