例題:
從鍵盤輸入字符串,要求將讀取到的整行字符串轉(zhuǎn)成大寫輸出。
然后繼續(xù)進(jìn)行輸入操作,直至當(dāng)輸入“e”或者“exit”時(shí),退出程序。
package com.atguigu.java;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import org.junit.Test;
public class TestOtherStream {
/*
* 標(biāo)準(zhǔn)的輸入輸出流:
* 標(biāo)準(zhǔn)的輸出流:System.out
* 標(biāo)準(zhǔn)的輸入流:System.in(是InputStream類型的,都是字節(jié)流)
*
* 題目:
* 從鍵盤輸入字符串,要求將讀取到的整行字符串轉(zhuǎn)成大寫輸出,
* 然后繼續(xù)進(jìn)行輸入操作,直至當(dāng)輸入“e”或者“exit”時(shí),退出程序。
*/
@Test
public void test2(){
BufferedReader br = null;
try {
InputStream is = System.in;//鍵盤輸入的字母是字節(jié)流
InputStreamReader isr = new InputStreamReader(is);//將字節(jié)流轉(zhuǎn)換成字符流
br = new BufferedReader(isr);
String str;
while(true){
System.out.println("請輸入字符串:");
str = br.readLine();
if(str.equalsIgnoreCase("e") || str.equalsIgnoreCase("exit")){
break;
}
String str1 = str.toUpperCase();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(br != null){
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/*
* 如何實(shí)現(xiàn)字節(jié)流與字符流之間的轉(zhuǎn)換
* 轉(zhuǎn)換流:InputStreamReader OutputStreamWriter
* 編碼:字符串---->字節(jié)數(shù)組
* 解碼:字節(jié)數(shù)組---->字符串
*/
@Test
public void test1(){
BufferedReader br = null;
BufferedWriter bw = null;
try {
//解碼
File file = new File("1.txt");
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis, "GBK");
br = new BufferedReader(isr);
//編碼
File file1 = new File("2.txt");
FileOutputStream fos = new FileOutputStream(file1);
OutputStreamWriter osw = new OutputStreamWriter(fos, "GBK");
bw = new BufferedWriter(osw);
String str;
while((str = br.readLine()) != null){
bw.write(str);
bw.newLine();
bw.flush();
}
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(bw != null){
try {
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(br != null){
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}