您的位置:首页 > 其它

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

2014-03-02 23:04 302 查看
/*

 * 读取键盘输入

 * 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();

}

 

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: