Java 轉換流:InputStreamReader & OutputStreamWriter package com.io.review; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.Fi ...
Java 轉換流:InputStreamReader & OutputStreamWriter
package com.io.review;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import org.junit.Test;
/**
* 轉換流:InputStreamReader & OutputStreamWriter
*/
public class BufferedStreamCopy {
/*
* 編碼 1 【編碼:字元串 -> 位元組數組】
*/
@Test
public void coding() {
String str = "自定義編碼 嘿 Siri !";
BufferedWriter bw = null;
try {
// 將str 寫入當前項目下./hello.txt 文件中
FileOutputStream fos = new FileOutputStream("./hello.txt");
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");// 此處也可指定編碼格式
bw = new BufferedWriter(osw);
bw.write(str);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bw != null) {
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/*
* 解碼 1 【解碼:位元組數組 -> 字元串】
*/
@Test
public void decode() {
BufferedReader br = null;
try {
InputStream in = System.in;
InputStreamReader isr = new InputStreamReader(in);
br = new BufferedReader(isr);
String str = null;
while ((str = br.readLine()) != null) {
System.out.println("---" + str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/*
* 解碼 2
*
* 從鍵盤輸入字元串,要求將讀取到的整行字元串轉成大寫輸出。當輸入“e”或者“exit”時,退出程式。
*/
@Test
public void decode2() {
BufferedReader br = null;
try {
InputStream in = System.in;
InputStreamReader sir = new InputStreamReader(in);
br = new BufferedReader(sir);
String str = null;
while ((str = br.readLine()) != null) {
// 忽略大小寫判斷是否 e或 exit
if (str.equalsIgnoreCase("e") || str.equalsIgnoreCase("exit")) {
System.out.println("程式結束!!");
break;
} else {
// 輸入的字元轉換成大寫
String upperCase = str.toUpperCase();
System.out.println(upperCase);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/*
* 解碼 3
*/
@Test
public void decode3() {
BufferedReader br = null;
try {
FileInputStream fis = new FileInputStream("./hello.txt");
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
br = new BufferedReader(isr);
String str = null;
while ((str = br.readLine()) != null) {
System.out.println(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}