文檔版本 | 開發(fā)工具 | 測(cè)試平臺(tái) | 工程名字 | 日期 | 作者 | 備注 |
---|---|---|---|---|---|---|
V1.0 | 2016.03.22 | lutianfei | none |
[TOC]
轉(zhuǎn)換流出現(xiàn)的原因及思想
- 由于字節(jié)流操作中文不是特別方便棍厌,所以童本,java就提供了
轉(zhuǎn)換流
原探。 -
字符流
=字節(jié)流
+編碼表
柴底。
編碼表
- 由字符及其對(duì)應(yīng)的數(shù)值組成的一張表
常見編碼表
- 計(jì)算機(jī)只能識(shí)別二進(jìn)制數(shù)據(jù),早期由來(lái)是電信號(hào)莫矗。為了方便應(yīng)用計(jì)算機(jī)飒硅,讓它可以識(shí)別各個(gè)國(guó)家的文字。
- ASCII:美國(guó)標(biāo)準(zhǔn)信息交換碼趣苏。
- 用一個(gè)字節(jié)的7位可以表示狡相。
- ISO8859-1:拉丁碼表梯轻。歐洲碼表
- 用一個(gè)字節(jié)的8位表示食磕。
- GB2312:中國(guó)的中文編碼表。
- GBK:中國(guó)的中文編碼表升級(jí)喳挑,融合了更多的中文文字符號(hào)彬伦。
- GB18030:GBK的取代版本
- BIG-5碼 :通行于臺(tái)灣、香港地區(qū)的一個(gè)繁體字編碼方案伊诵,俗稱“大五碼”单绑。
- Unicode:國(guó)際標(biāo)準(zhǔn)碼,融合了多種文字曹宴。
- 所有文字都用兩個(gè)字節(jié)來(lái)表示,Java語(yǔ)言使用的就是unicode
- UTF-8:最多用三個(gè)字節(jié)來(lái)表示一個(gè)字符搂橙。
- UTF-8不同,它定義了一種“區(qū)間規(guī)則”笛坦,這種規(guī)則可以和ASCII編碼保持最大程度的兼容:
- 它將Unicode編碼為00000000-0000007F的字符区转,用單個(gè)字節(jié)來(lái)表示
- 它將Unicode編碼為00000080-000007FF的字符用兩個(gè)字節(jié)表示
- 它將Unicode編碼為00000800-0000FFFF的字符用3字節(jié)表示
字符串中的編碼問(wèn)題
-
編碼
- byte[] getBytes(String charsetName):使用指定的字符集合把字符串編碼為字節(jié)數(shù)組
-
解碼
- String(byte[] bytes, String charsetName):通過(guò)指定的字符集解碼字節(jié)數(shù)組
-
編碼:把看得懂的變成看不懂的
- String -- byte[]
-
解碼:把看不懂的變成看得懂的
- byte[] -- String
public class StringDemo {
public static void main(String[] args) throws UnsupportedEncodingException {
String s = "你好";
// String -- byte[]
byte[] bys = s.getBytes(); // [-60, -29, -70, -61]
// byte[] bys = s.getBytes("GBK");// [-60, -29, -70, -61]
// byte[] bys = s.getBytes("UTF-8");// [-28, -67, -96, -27, -91, -67]
System.out.println(Arrays.toString(bys));
// byte[] -- String
String ss = new String(bys); // 你好
// String ss = new String(bys, "GBK"); // 你好
// String ss = new String(bys, "UTF-8"); // ???
System.out.println(ss);
}
}
轉(zhuǎn)換流概述
-
OutputStreamWriter 字符輸出流
-
OutputStreamWriter
(OutputStream out):根據(jù)默認(rèn)編碼把字節(jié)流的數(shù)據(jù)轉(zhuǎn)換為字符流 -
OutputStreamWriter
(OutputStream out,String charsetName):根據(jù)指定編碼把字節(jié)流數(shù)據(jù)轉(zhuǎn)換為字符流
-
-
InputStreamReader 字符輸入流
- InputStreamReader(InputStream is):用默認(rèn)的編碼讀取數(shù)據(jù)
- InputStreamReader(InputStream is,String charsetName):用指定的編碼讀取數(shù)據(jù)
OutputStreamWriter寫數(shù)據(jù)
- OutputStreamWriter寫數(shù)據(jù)方法
- public void write(int c):寫一個(gè)字符
- public void write(char[] cbuf):寫一個(gè)字符數(shù)組
- public void write(char[] cbuf,int off,int len):寫一個(gè)字符數(shù)組的一部分
- public void write(String str):寫一個(gè)字符串
- public void write(String str,int off,int len):寫一個(gè)字符串的一部分
public class OutputStreamWriterDemo {
public static void main(String[] args) throws IOException {
// 創(chuàng)建對(duì)象
// OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(
// "osw.txt")); // 默認(rèn)GBK
// OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(
// "osw.txt"), "GBK"); // 指定GBK
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(
"osw.txt"), "UTF-8"); // 指定UTF-8
// 寫數(shù)據(jù)
osw.write("中國(guó)");
// 釋放資源
osw.close();
}
}
字符流操作要注意的問(wèn)題
- flush()和close()的區(qū)別
- A:close()關(guān)閉流對(duì)象,但是先刷新一次緩沖區(qū)版扩。關(guān)閉之后废离,流對(duì)象不可以繼續(xù)再使用了。
- B:flush()僅僅刷新緩沖區(qū),刷新之后礁芦,流對(duì)象還可以繼續(xù)使用蜻韭。
public class OutputStreamWriterDemo {
public static void main(String[] args) throws IOException {
// 創(chuàng)建對(duì)象
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(
"osw2.txt"));
// 寫數(shù)據(jù)
// public void write(int c):寫一個(gè)字符
// osw.write('a');
// osw.write(97);
// 為什么數(shù)據(jù)沒(méi)有進(jìn)去呢?
// 原因是:字符 = 2字節(jié)
// 文件中數(shù)據(jù)存儲(chǔ)的基本單位是字節(jié)。
// void flush()
// public void write(char[] cbuf):寫一個(gè)字符數(shù)組
// char[] chs = {'a','b','c','d','e'};
// osw.write(chs);
// public void write(char[] cbuf,int off,int len):寫一個(gè)字符數(shù)組的一部分
// osw.write(chs,1,3);
// public void write(String str):寫一個(gè)字符串
// osw.write("我愛(ài)林青霞");
// public void write(String str,int off,int len):寫一個(gè)字符串的一部分
osw.write("我愛(ài)林青霞", 2, 3);
// 刷新緩沖區(qū)
osw.flush();
// osw.write("我愛(ài)林青霞", 2, 3);
// 釋放資源
osw.close();
// java.io.IOException: Stream closed
// osw.write("我愛(ài)林青霞", 2, 3);
}
}
InputStreamReader讀數(shù)據(jù)
- 讀數(shù)據(jù)方法
- int read():一次讀取一個(gè)字符
- int read(char[] chs):一次讀取一個(gè)字符數(shù)組
public class InputStreamReaderDemo {
public static void main(String[] args) throws IOException {
// 創(chuàng)建對(duì)象
// InputStreamReader isr = new InputStreamReader(new FileInputStream(
// "osw.txt"));
// InputStreamReader isr = new InputStreamReader(new FileInputStream(
// "osw.txt"), "GBK");
InputStreamReader isr = new InputStreamReader(new FileInputStream(
"osw.txt"), "UTF-8");
// 讀取數(shù)據(jù)
// 一次讀取一個(gè)字符
int ch = 0;
while ((ch = isr.read()) != -1) {
System.out.print((char) ch);
}
// 釋放資源
isr.close();
}
}
public class InputStreamReaderDemo {
public static void main(String[] args) throws IOException {
// 創(chuàng)建對(duì)象
InputStreamReader isr = new InputStreamReader(new FileInputStream(
"StringDemo.java"));
// 一次讀取一個(gè)字符
// int ch = 0;
// while ((ch = isr.read()) != -1) {
// System.out.print((char) ch);
// }
// 一次讀取一個(gè)字符數(shù)組
char[] chs = new char[1024];
int len = 0;
while ((len = isr.read(chs)) != -1) {
System.out.print(new String(chs, 0, len));
}
// 釋放資源
isr.close();
}
}
字符流復(fù)制文本文件
- 把當(dāng)前項(xiàng)目目錄下的a.txt內(nèi)容復(fù)制到當(dāng)前項(xiàng)目目錄下的b.txt中
/*
* 需求:把當(dāng)前項(xiàng)目目錄下的a.txt內(nèi)容復(fù)制到當(dāng)前項(xiàng)目目錄下的b.txt中
*
* 數(shù)據(jù)源:
* a.txt -- 讀取數(shù)據(jù) -- 字符轉(zhuǎn)換流 -- InputStreamReader
* 目的地:
* b.txt -- 寫出數(shù)據(jù) -- 字符轉(zhuǎn)換流 -- OutputStreamWriter
*/
public class CopyFileDemo {
public static void main(String[] args) throws IOException {
// 封裝數(shù)據(jù)源
InputStreamReader isr = new InputStreamReader(new FileInputStream(
"a.txt"));
// 封裝目的地
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(
"b.txt"));
// 讀寫數(shù)據(jù)
// 方式1
// int ch = 0;
// while ((ch = isr.read()) != -1) {
// osw.write(ch);
// }
// 方式2
char[] chs = new char[1024];
int len = 0;
while ((len = isr.read(chs)) != -1) {
osw.write(chs, 0, len);
// osw.flush();
}
// 釋放資源
osw.close();
isr.close();
}
}
- 把c:\a.txt內(nèi)容復(fù)制到d:\b.txt中
轉(zhuǎn)換流的簡(jiǎn)化寫法
轉(zhuǎn)換流的名字比較長(zhǎng)柿扣,而我們常見的操作都是按照本地默認(rèn)編碼實(shí)現(xiàn)的肖方,所以,為了簡(jiǎn)化我們的書寫未状,轉(zhuǎn)換流提供了對(duì)應(yīng)的子類俯画。
FileWriter寫數(shù)據(jù)
FileReader讀取數(shù)據(jù)
-
OutputStreamWriter = FileOutputStream + 編碼表(GBK)
- FileWriter = FileOutputStream + 編碼表(GBK)
-
InputStreamReader = FileInputStream + 編碼表(GBK)
- FileReader = FileInputStream + 編碼表(GBK)
/*
* 由于我們常見的操作都是使用本地默認(rèn)編碼,所以娩践,不用指定編碼活翩。
* 而轉(zhuǎn)換流的名稱有點(diǎn)長(zhǎng)烹骨,所以,Java就提供了其子類供我們使用材泄。
* OutputStreamWriter = FileOutputStream + 編碼表(GBK)
* 需求:把當(dāng)前項(xiàng)目目錄下的a.txt內(nèi)容復(fù)制到當(dāng)前項(xiàng)目目錄下的b.txt中
*
* 數(shù)據(jù)源:
* a.txt -- 讀取數(shù)據(jù) -- 字符轉(zhuǎn)換流 -- InputStreamReader -- FileReader
* 目的地:
* b.txt -- 寫出數(shù)據(jù) -- 字符轉(zhuǎn)換流 -- OutputStreamWriter -- FileWriter
*/
public class CopyFileDemo2 {
public static void main(String[] args) throws IOException {
// 封裝數(shù)據(jù)源
FileReader fr = new FileReader("a.txt");
// 封裝目的地
FileWriter fw = new FileWriter("b.txt");
// 一次一個(gè)字符
// int ch = 0;
// while ((ch = fr.read()) != -1) {
// fw.write(ch);
// }
// 一次一個(gè)字符數(shù)組
char[] chs = new char[1024];
int len = 0;
while ((len = fr.read(chs)) != -1) {
fw.write(chs, 0, len);
fw.flush();
}
// 釋放資源
fw.close();
fr.close();
}
}
字符緩沖流
- 字符流為了高效讀寫沮焕,也提供了對(duì)應(yīng)的字符緩沖流。
- BufferedWriter:字符緩沖輸出流
- BufferedReader:字符緩沖輸入流
BufferedWriter:字符緩沖輸出流
- 將文本寫入字符輸出流拉宗,緩沖各個(gè)字符峦树,從而提供單個(gè)字符、數(shù)組和字符串的高效寫入旦事。
- 可以指定緩沖區(qū)的大小魁巩,或者接受默認(rèn)的大小。在大多數(shù)情況下姐浮,默認(rèn)值就足夠大了谷遂。
public class BufferedWriterDemo {
public static void main(String[] args) throws IOException {
// BufferedWriter(Writer out)
// BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
// new FileOutputStream("bw.txt")));
BufferedWriter bw = new BufferedWriter(new FileWriter("bw.txt"));
bw.write("hello");
bw.write("world");
bw.write("java");
bw.flush();
bw.close();
}
}
BufferedReader
- 從字符輸入流中讀取文本,緩沖各個(gè)字符卖鲤,從而實(shí)現(xiàn)字符肾扰、數(shù)組和行的高效讀取。
- 可以指定緩沖區(qū)的大小蛋逾,或者可使用默認(rèn)的大小集晚。大多數(shù)情況下,默認(rèn)值就足夠大了区匣。
public class BufferedReaderDemo {
public static void main(String[] args) throws IOException {
// 創(chuàng)建字符緩沖輸入流對(duì)象
BufferedReader br = new BufferedReader(new FileReader("bw.txt"));
// 方式1
// int ch = 0;
// while ((ch = br.read()) != -1) {
// System.out.print((char) ch);
// }
// 方式2
char[] chs = new char[1024];
int len = 0;
while ((len = br.read(chs)) != -1) {
System.out.print(new String(chs, 0, len));
}
// 釋放資源
br.close();
}
}
- 文本復(fù)制例子
/*
* 需求:把當(dāng)前項(xiàng)目目錄下的a.txt內(nèi)容復(fù)制到當(dāng)前項(xiàng)目目錄下的b.txt中
*
* 數(shù)據(jù)源:
* a.txt -- 讀取數(shù)據(jù) -- 字符轉(zhuǎn)換流 -- InputStreamReader -- FileReader -- BufferedReader
* 目的地:
* b.txt -- 寫出數(shù)據(jù) -- 字符轉(zhuǎn)換流 -- OutputStreamWriter -- FileWriter -- BufferedWriter
*/
public class CopyFileDemo {
public static void main(String[] args) throws IOException {
// 封裝數(shù)據(jù)源
BufferedReader br = new BufferedReader(new FileReader("a.txt"));
// 封裝目的地
BufferedWriter bw = new BufferedWriter(new FileWriter("b.txt"));
// 兩種方式其中的一種一次讀寫一個(gè)字符數(shù)組
char[] chs = new char[1024];
int len = 0;
while ((len = br.read(chs)) != -1) {
bw.write(chs, 0, len);
bw.flush();
}
// 釋放資源
bw.close();
br.close();
}
}
字符緩沖流的特殊方法
- BufferedWriter:
- public void newLine():根據(jù)系統(tǒng)來(lái)決定換行符
- BufferedReader:
- public String readLine():一次讀取一行數(shù)據(jù)
- 包含該行內(nèi)容的字符串偷拔,不包含任何行終止符,如果已到達(dá)流末尾亏钩,則返回
null
- 包含該行內(nèi)容的字符串偷拔,不包含任何行終止符,如果已到達(dá)流末尾亏钩,則返回
- public String readLine():一次讀取一行數(shù)據(jù)
public class BufferedDemo {
public static void main(String[] args) throws IOException {
// write();
read();
}
private static void read() throws IOException {
// 創(chuàng)建字符緩沖輸入流對(duì)象
BufferedReader br = new BufferedReader(new FileReader("bw2.txt"));
// 最終版代碼
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
//釋放資源
br.close();
}
private static void write() throws IOException {
// 創(chuàng)建字符緩沖輸出流對(duì)象
BufferedWriter bw = new BufferedWriter(new FileWriter("bw2.txt"));
for (int x = 0; x < 10; x++) {
bw.write("hello" + x);
// bw.write("\r\n");
bw.newLine();
bw.flush();
}
bw.close();
}
}
- 字符緩沖流特殊功能復(fù)制文本文件)(必會(huì))
/*
* 需求:把當(dāng)前項(xiàng)目目錄下的a.txt內(nèi)容復(fù)制到當(dāng)前項(xiàng)目目錄下的b.txt中
*
* 數(shù)據(jù)源:
* a.txt -- 讀取數(shù)據(jù) -- 字符轉(zhuǎn)換流 -- InputStreamReader -- FileReader -- BufferedReader
* 目的地:
* b.txt -- 寫出數(shù)據(jù) -- 字符轉(zhuǎn)換流 -- OutputStreamWriter -- FileWriter -- BufferedWriter
*/
public class CopyFileDemo2 {
public static void main(String[] args) throws IOException {
// 封裝數(shù)據(jù)源
BufferedReader br = new BufferedReader(new FileReader("a.txt"));
// 封裝目的地
BufferedWriter bw = new BufferedWriter(new FileWriter("b.txt"));
// 讀寫數(shù)據(jù)
String line = null;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
bw.flush();
}
// 釋放資源
bw.close();
br.close();
}
}
IO流小結(jié)
- 字節(jié)流
- 字節(jié)輸入流
- 字節(jié)輸出流
- 字符流
- 字符輸入流
- 字符輸出流
IO流練習(xí)
- 復(fù)制文本文件
/*
* 復(fù)制文本文件
*
* 分析:
* 而字符流有5種方式莲绰,所以做這個(gè)題目我們有5種方式。推薦掌握第5種铸屉。
* 數(shù)據(jù)源:
* c:\\a.txt -- FileReader -- BufferdReader
* 目的地:
* d:\\b.txt -- FileWriter -- BufferedWriter
*/
public class CopyFileDemo {
public static void main(String[] args) throws IOException {
String srcString = "c:\\a.txt";
String destString = "d:\\b.txt";
// method1(srcString, destString);
// method2(srcString, destString);
// method3(srcString, destString);
// method4(srcString, destString);
method5(srcString, destString);
}
// 字符緩沖流一次讀寫一個(gè)字符串
private static void method5(String srcString, String destString)
throws IOException {
BufferedReader br = new BufferedReader(new FileReader(srcString));
BufferedWriter bw = new BufferedWriter(new FileWriter(destString));
String line = null;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
bw.flush();
}
bw.close();
br.close();
}
// 字符緩沖流一次讀寫一個(gè)字符數(shù)組
private static void method4(String srcString, String destString)
throws IOException {
BufferedReader br = new BufferedReader(new FileReader(srcString));
BufferedWriter bw = new BufferedWriter(new FileWriter(destString));
char[] chs = new char[1024];
int len = 0;
while ((len = br.read(chs)) != -1) {
bw.write(chs, 0, len);
}
bw.close();
br.close();
}
// 字符緩沖流一次讀寫一個(gè)字符
private static void method3(String srcString, String destString)
throws IOException {
BufferedReader br = new BufferedReader(new FileReader(srcString));
BufferedWriter bw = new BufferedWriter(new FileWriter(destString));
int ch = 0;
while ((ch = br.read()) != -1) {
bw.write(ch);
}
bw.close();
br.close();
}
// 基本字符流一次讀寫一個(gè)字符數(shù)組
private static void method2(String srcString, String destString)
throws IOException {
FileReader fr = new FileReader(srcString);
FileWriter fw = new FileWriter(destString);
char[] chs = new char[1024];
int len = 0;
while ((len = fr.read(chs)) != -1) {
fw.write(chs, 0, len);
}
fw.close();
fr.close();
}
// 基本字符流一次讀寫一個(gè)字符
private static void method1(String srcString, String destString)
throws IOException {
FileReader fr = new FileReader(srcString);
FileWriter fw = new FileWriter(destString);
int ch = 0;
while ((ch = fr.read()) != -1) {
fw.write(ch);
}
fw.close();
fr.close();
}
}
- 復(fù)制圖片
/*
* 復(fù)制圖片
*
* 分析:
* 復(fù)制數(shù)據(jù)钉蒲,如果我們知道用記事本打開并能夠讀懂,就用字符流彻坛,否則用字節(jié)流顷啼。
* 通過(guò)該原理,我們知道我們應(yīng)該采用字節(jié)流昌屉。
* 而字節(jié)流有4種方式钙蒙,所以做這個(gè)題目我們有4種方式。推薦掌握第4種间驮。
*
* 數(shù)據(jù)源:
* c:\\a.jpg -- FileInputStream -- BufferedInputStream
* 目的地:
* d:\\b.jpg -- FileOutputStream -- BufferedOutputStream
*/
public class CopyImageDemo {
public static void main(String[] args) throws IOException {
// 使用字符串作為路徑
// String srcString = "c:\\a.jpg";
// String destString = "d:\\b.jpg";
// 使用File對(duì)象做為參數(shù)
File srcFile = new File("c:\\a.jpg");
File destFile = new File("d:\\b.jpg");
// method1(srcFile, destFile);
// method2(srcFile, destFile);
// method3(srcFile, destFile);
method4(srcFile, destFile);
}
// 字節(jié)緩沖流一次讀寫一個(gè)字節(jié)數(shù)組
private static void method4(File srcFile, File destFile) throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
srcFile));
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(destFile));
byte[] bys = new byte[1024];
int len = 0;
while ((len = bis.read(bys)) != -1) {
bos.write(bys, 0, len);
}
bos.close();
bis.close();
}
// 字節(jié)緩沖流一次讀寫一個(gè)字節(jié)
private static void method3(File srcFile, File destFile) throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
srcFile));
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(destFile));
int by = 0;
while ((by = bis.read()) != -1) {
bos.write(by);
}
bos.close();
bis.close();
}
// 基本字節(jié)流一次讀寫一個(gè)字節(jié)數(shù)組
private static void method2(File srcFile, File destFile) throws IOException {
FileInputStream fis = new FileInputStream(srcFile);
FileOutputStream fos = new FileOutputStream(destFile);
byte[] bys = new byte[1024];
int len = 0;
while ((len = fis.read(bys)) != -1) {
fos.write(bys, 0, len);
}
fos.close();
fis.close();
}
// 基本字節(jié)流一次讀寫一個(gè)字節(jié)
private static void method1(File srcFile, File destFile) throws IOException {
FileInputStream fis = new FileInputStream(srcFile);
FileOutputStream fos = new FileOutputStream(destFile);
int by = 0;
while ((by = fis.read()) != -1) {
fos.write(by);
}
fos.close();
fis.close();
}
}
- 把ArrayList集合中的字符串?dāng)?shù)據(jù)存儲(chǔ)到文本文件
/*
* 需求:把ArrayList集合中的字符串?dāng)?shù)據(jù)存儲(chǔ)到文本文件
*
* 分析:
* 通過(guò)題目的意思我們可以知道如下的一些內(nèi)容躬厌,
* ArrayList集合里存儲(chǔ)的是字符串。
* 遍歷ArrayList集合,把數(shù)據(jù)獲取到扛施。
* 然后存儲(chǔ)到文本文件中鸿捧。
* 文本文件說(shuō)明使用字符流。
*
* 數(shù)據(jù)源:
* ArrayList<String> -- 遍歷得到每一個(gè)字符串?dāng)?shù)據(jù)
* 目的地:
* a.txt -- FileWriter -- BufferedWriter
*/
public class ArrayListToFileDemo {
public static void main(String[] args) throws IOException {
// 封裝數(shù)據(jù)源(創(chuàng)建集合對(duì)象)
ArrayList<String> array = new ArrayList<String>();
array.add("hello");
array.add("world");
array.add("java");
// 封裝目的地
BufferedWriter bw = new BufferedWriter(new FileWriter("a.txt"));
// 遍歷集合
for (String s : array) {
// 寫數(shù)據(jù)
bw.write(s);
bw.newLine();
bw.flush();
}
// 釋放資源
bw.close();
}
}
- 從文本文件中讀取數(shù)據(jù)(每一行為一個(gè)字符串?dāng)?shù)據(jù))到集合中妄荔,并遍歷集合
/*
* 需求:從文本文件中讀取數(shù)據(jù)(每一行為一個(gè)字符串?dāng)?shù)據(jù))到集合中泼菌,并遍歷集合
*
* 分析:
* 通過(guò)題目的意思我們可以知道如下的一些內(nèi)容篷角,
* 數(shù)據(jù)源是一個(gè)文本文件阱缓。
* 目的地是一個(gè)集合。
* 而且元素是字符串。
*
* 數(shù)據(jù)源:
* b.txt -- FileReader -- BufferedReader
* 目的地:
* ArrayList<String>
*/
public class FileToArrayListDemo {
public static void main(String[] args) throws IOException {
// 封裝數(shù)據(jù)源
BufferedReader br = new BufferedReader(new FileReader("b.txt"));
// 封裝目的地(創(chuàng)建集合對(duì)象)
ArrayList<String> array = new ArrayList<String>();
// 讀取數(shù)據(jù)存儲(chǔ)到集合中
String line = null;
while ((line = br.readLine()) != null) {
array.add(line);
}
// 釋放資源
br.close();
// 遍歷集合
for (String s : array) {
System.out.println(s);
}
}
}
- 隨機(jī)獲取文本中的名字
/*
* 需求:我有一個(gè)文本文件中存儲(chǔ)了幾個(gè)名稱错森,請(qǐng)大家寫一個(gè)程序?qū)崿F(xiàn)隨機(jī)獲取一個(gè)人的名字蜗侈。
*
* 分析:
* A:把文本文件中的數(shù)據(jù)存儲(chǔ)到集合中
* B:隨機(jī)產(chǎn)生一個(gè)索引
* C:根據(jù)該索引獲取一個(gè)值
*/
public class GetName {
public static void main(String[] args) throws IOException {
// 把文本文件中的數(shù)據(jù)存儲(chǔ)到集合中
BufferedReader br = new BufferedReader(new FileReader("b.txt"));
ArrayList<String> array = new ArrayList<String>();
String line = null;
while ((line = br.readLine()) != null) {
array.add(line);
}
br.close();
// 隨機(jī)產(chǎn)生一個(gè)索引
Random r = new Random();
int index = r.nextInt(array.size());
// 根據(jù)該索引獲取一個(gè)值
String name = array.get(index);
System.out.println("該幸運(yùn)者是:" + name);
}
}
- 復(fù)制單極文件夾
/*
* 需求:復(fù)制單極文件夾
*
* 數(shù)據(jù)源:e:\\demo
* 目的地:e:\\test
*
* 分析:
* A:封裝目錄
* B:獲取該目錄下的所有文本的File數(shù)組
* C:遍歷該File數(shù)組豺瘤,得到每一個(gè)File對(duì)象
* D:把該File進(jìn)行復(fù)制
*/
public class CopyFolderDemo {
public static void main(String[] args) throws IOException {
// 封裝目錄
File srcFolder = new File("e:\\demo");
// 封裝目的地
File destFolder = new File("e:\\test");
// 如果目的地文件夾不存在,就創(chuàng)建
if (!destFolder.exists()) {
destFolder.mkdir();
}
// 獲取該目錄下的所有文本的File數(shù)組
File[] fileArray = srcFolder.listFiles();
// 遍歷該File數(shù)組渊鞋,得到每一個(gè)File對(duì)象
for (File file : fileArray) {
// System.out.println(file);
// 數(shù)據(jù)源:e:\\demo\\e.mp3
// 目的地:e:\\test\\e.mp3
String name = file.getName(); // e.mp3
File newFile = new File(destFolder, name); // e:\\test\\e.mp3
copyFile(file, newFile);
}
}
private static void copyFile(File file, File newFile) throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
file));
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(newFile));
byte[] bys = new byte[1024];
int len = 0;
while ((len = bis.read(bys)) != -1) {
bos.write(bys, 0, len);
}
bos.close();
bis.close();
}
}
- 復(fù)制單極文件夾中指定文件并修改文件名稱
/*
* 需求:復(fù)制指定目錄下的指定文件尝丐,并修改后綴名。
* 指定的文件是:.java文件。
* 指定的后綴名是:.jad
* 指定的目錄是:jad
*
* 數(shù)據(jù)源:e:\\java\\A.java
* 目的地:e:\\jad\\A.jad
*
* 分析:
* A:封裝目錄
* B:獲取該目錄下的java文件的File數(shù)組
* C:遍歷該File數(shù)組蛤迎,得到每一個(gè)File對(duì)象
* D:把該File進(jìn)行復(fù)制
* E:在目的地目錄下改名
*/
public class CopyFolderDemo {
public static void main(String[] args) throws IOException {
// 封裝目錄
File srcFolder = new File("e:\\java");
// 封裝目的地
File destFolder = new File("e:\\jad");
// 如果目的地目錄不存在替裆,就創(chuàng)建
if (!destFolder.exists()) {
destFolder.mkdir();
}
// 獲取該目錄下的java文件的File數(shù)組
File[] fileArray = srcFolder.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return new File(dir, name).isFile() && name.endsWith(".java");
}
});
// 遍歷該File數(shù)組故黑,得到每一個(gè)File對(duì)象
for (File file : fileArray) {
// System.out.println(file);
// 數(shù)據(jù)源:e:\java\DataTypeDemo.java
// 目的地:e:\\jad\DataTypeDemo.java
String name = file.getName();
File newFile = new File(destFolder, name);
copyFile(file, newFile);
}
// 在目的地目錄下改名
File[] destFileArray = destFolder.listFiles();
for (File destFile : destFileArray) {
// System.out.println(destFile);
// e:\jad\DataTypeDemo.java
// e:\\jad\\DataTypeDemo.jad
String name =destFile.getName(); //DataTypeDemo.java
String newName = name.replace(".java", ".jad");//DataTypeDemo.jad
File newFile = new File(destFolder,newName);
destFile.renameTo(newFile);
}
}
private static void copyFile(File file, File newFile) throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
file));
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(newFile));
byte[] bys = new byte[1024];
int len = 0;
while ((len = bis.read(bys)) != -1) {
bos.write(bys, 0, len);
}
bos.close();
bis.close();
}
}
- 復(fù)制多極文件夾
/*
* 需求:復(fù)制多極文件夾
*
* 數(shù)據(jù)源:E:\JavaSE\day21\code\demos
* 目的地:E:\\
*
* 分析:
* A:封裝數(shù)據(jù)源File
* B:封裝目的地File
* C:判斷該File是文件夾還是文件
* a:是文件夾
* 就在目的地目錄下創(chuàng)建該文件夾
* 獲取該File對(duì)象下的所有文件或者文件夾File對(duì)象
* 遍歷得到每一個(gè)File對(duì)象
* 回到C
* b:是文件
* 就復(fù)制(字節(jié)流)
*/
public class CopyFoldersDemo {
public static void main(String[] args) throws IOException {
// 封裝數(shù)據(jù)源File
File srcFile = new File("E:\\JavaSE\\day21\\code\\demos");
// 封裝目的地File
File destFile = new File("E:\\");
// 復(fù)制文件夾的功能
copyFolder(srcFile, destFile);
}
private static void copyFolder(File srcFile, File destFile)
throws IOException {
// 判斷該File是文件夾還是文件
if (srcFile.isDirectory()) {
// 文件夾
File newFolder = new File(destFile, srcFile.getName());
newFolder.mkdir();
// 獲取該File對(duì)象下的所有文件或者文件夾File對(duì)象
File[] fileArray = srcFile.listFiles();
for (File file : fileArray) {
copyFolder(file, newFolder);
}
} else {
// 文件
File newFile = new File(destFile, srcFile.getName());
copyFile(srcFile, newFile);
}
}
private static void copyFile(File srcFile, File newFile) throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
srcFile));
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(newFile));
byte[] bys = new byte[1024];
int len = 0;
while ((len = bis.read(bys)) != -1) {
bos.write(bys, 0, len);
}
bos.close();
bis.close();
}
}
- 鍵盤錄入5個(gè)學(xué)生信息(姓名,語(yǔ)文成績(jī),數(shù)學(xué)成績(jī),英語(yǔ)成績(jī)),按照總分從高到低存入文本文件
/*
* 鍵盤錄入5個(gè)學(xué)生信息(姓名,語(yǔ)文成績(jī),數(shù)學(xué)成績(jī),英語(yǔ)成績(jī)),按照總分從高到低存入文本文件
*
* 分析:
* A:創(chuàng)建學(xué)生類
* B:創(chuàng)建集合對(duì)象
* TreeSet<Student>
* C:鍵盤錄入學(xué)生信息存儲(chǔ)到集合
* D:遍歷集合概耻,把數(shù)據(jù)寫到文本文件
*/
public class StudentDemo {
public static void main(String[] args) throws IOException {
// 創(chuàng)建集合對(duì)象
TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
int num = s2.getSum() - s1.getSum();
int num2 = num == 0 ? s1.getChinese() - s2.getChinese() : num;
int num3 = num2 == 0 ? s1.getMath() - s2.getMath() : num2;
int num4 = num3 == 0 ? s1.getEnglish() - s2.getEnglish() : num3;
int num5 = num4 == 0 ? s1.getName().compareTo(s2.getName())
: num4;
return num5;
}
});
// 鍵盤錄入學(xué)生信息存儲(chǔ)到集合
for (int x = 1; x <= 5; x++) {
Scanner sc = new Scanner(System.in);
System.out.println("請(qǐng)錄入第" + x + "個(gè)的學(xué)習(xí)信息");
System.out.println("姓名:");
String name = sc.nextLine();
System.out.println("語(yǔ)文成績(jī):");
int chinese = sc.nextInt();
System.out.println("數(shù)學(xué)成績(jī):");
int math = sc.nextInt();
System.out.println("英語(yǔ)成績(jī):");
int english = sc.nextInt();
// 創(chuàng)建學(xué)生對(duì)象
Student s = new Student();
s.setName(name);
s.setChinese(chinese);
s.setMath(math);
s.setEnglish(english);
// 把學(xué)生信息添加到集合
ts.add(s);
}
// 遍歷集合侦高,把數(shù)據(jù)寫到文本文件
BufferedWriter bw = new BufferedWriter(new FileWriter("students.txt"));
bw.write("學(xué)生信息如下:");
bw.newLine();
bw.flush();
bw.write("姓名,語(yǔ)文成績(jī),數(shù)學(xué)成績(jī),英語(yǔ)成績(jī)");
bw.newLine();
bw.flush();
for (Student s : ts) {
StringBuilder sb = new StringBuilder();
sb.append(s.getName()).append(",").append(s.getChinese())
.append(",").append(s.getMath()).append(",")
.append(s.getEnglish());
bw.write(sb.toString());
bw.newLine();
bw.flush();
}
// 釋放資源
bw.close();
System.out.println("學(xué)習(xí)信息存儲(chǔ)完畢");
}
}
- 已知s.txt文件中有這樣的一個(gè)字符串:“hcexfgijkamdnoqrzstuvwybpl”
- 請(qǐng)編寫程序讀取數(shù)據(jù)內(nèi)容嫉柴,把數(shù)據(jù)排序后寫入ss.txt中。
/*
* 已知s.txt文件中有這樣的一個(gè)字符串:“hcexfgijkamdnoqrzstuvwybpl”
* 請(qǐng)編寫程序讀取數(shù)據(jù)內(nèi)容奉呛,把數(shù)據(jù)排序后寫入ss.txt中计螺。
*
* 分析:
* A:把s.txt這個(gè)文件給做出來(lái)
* B:讀取該文件的內(nèi)容,存儲(chǔ)到一個(gè)字符串中
* C:把字符串轉(zhuǎn)換為字符數(shù)組
* D:對(duì)字符數(shù)組進(jìn)行排序
* E:把排序后的字符數(shù)組轉(zhuǎn)換為字符串
* F:把字符串再次寫入ss.txt中
*/
public class StringDemo {
public static void main(String[] args) throws IOException {
// 讀取該文件的內(nèi)容瞧壮,存儲(chǔ)到一個(gè)字符串中
BufferedReader br = new BufferedReader(new FileReader("s.txt"));
String line = br.readLine();
br.close();
// 把字符串轉(zhuǎn)換為字符數(shù)組
char[] chs = line.toCharArray();
// 對(duì)字符數(shù)組進(jìn)行排序
Arrays.sort(chs);
// 把排序后的字符數(shù)組轉(zhuǎn)換為字符串
String s = new String(chs);
// 把字符串再次寫入ss.txt中
BufferedWriter bw = new BufferedWriter(new FileWriter("ss.txt"));
bw.write(s);
bw.newLine();
bw.flush();
bw.close();
}
}
- 用Reader模擬BufferedReader的readLine()功能
/*
* 用Reader模擬BufferedReader的readLine()功能
*
* readLine():一次讀取一行登馒,根據(jù)換行符判斷是否結(jié)束,只返回內(nèi)容咆槽,不返回?fù)Q行符
*/
public class MyBufferedReader {
private Reader r;
public MyBufferedReader(Reader r) {
this.r = r;
}
/*
* 思考:寫一個(gè)方法陈轿,返回值是一個(gè)字符串。
*/
public String readLine() throws IOException {
/*
* 我要返回一個(gè)字符串,我該怎么辦呢? 我們必須去看看r對(duì)象能夠讀取什么東西呢? 兩個(gè)讀取方法麦射,一次讀取一個(gè)字符或者一次讀取一個(gè)字符數(shù)組
* 那么蛾娶,我們要返回一個(gè)字符串,用哪個(gè)方法比較好呢? 我們很容易想到字符數(shù)組比較好潜秋,但是問(wèn)題來(lái)了蛔琅,就是這個(gè)數(shù)組的長(zhǎng)度是多長(zhǎng)呢?
* 根本就沒(méi)有辦法定義數(shù)組的長(zhǎng)度,你定義多長(zhǎng)都不合適峻呛。 所以罗售,只能選擇一次讀取一個(gè)字符。
* 但是呢钩述,這種方式的時(shí)候寨躁,我們?cè)僮x取下一個(gè)字符的時(shí)候,上一個(gè)字符就丟失了 所以切距,我們又應(yīng)該定義一個(gè)臨時(shí)存儲(chǔ)空間把讀取過(guò)的字符給存儲(chǔ)起來(lái)朽缎。
* 這個(gè)用誰(shuí)比較合適呢?數(shù)組,集合谜悟,字符串緩沖區(qū)三個(gè)可供選擇话肖。
* 經(jīng)過(guò)簡(jiǎn)單的分析,最終選擇使用字符串緩沖區(qū)對(duì)象葡幸。并且使用的是StringBuilder
*/
StringBuilder sb = new StringBuilder();
// 做這個(gè)讀取最麻煩的是判斷結(jié)束最筒,但是在結(jié)束之前應(yīng)該是一直讀取,直到-1
/*
hello
world
java
104101108108111
119111114108100
1069711897
*/
int ch = 0;
while ((ch = r.read()) != -1) { //104,101,108,108,111
if (ch == '\r') {
continue;
}
if (ch == '\n') {
return sb.toString(); //hello
} else {
sb.append((char)ch); //hello
}
}
// 為了防止數(shù)據(jù)丟失蔚叨,判斷sb的長(zhǎng)度不能大于0
if (sb.length() > 0) {
return sb.toString();
}
return null;
}
/*
* 先寫一個(gè)關(guān)閉方法
*/
public void close() throws IOException {
this.r.close();
}
}
- 自定義類模擬LineNumberReader的特有功能
- 獲取每次讀取數(shù)據(jù)的行號(hào)
public class MyLineNumberReaderTest {
public static void main(String[] args) throws IOException {
// MyLineNumberReader mlnr = new MyLineNumberReader(new FileReader(
// "my.txt"));
MyLineNumberReader2 mlnr = new MyLineNumberReader2(new FileReader(
"my.txt"));
// mlnr.setLineNumber(10);
// System.out.println(mlnr.getLineNumber());
// System.out.println(mlnr.getLineNumber());
// System.out.println(mlnr.getLineNumber());
String line = null;
while ((line = mlnr.readLine()) != null) {
System.out.println(mlnr.getLineNumber() + ":" + line);
}
mlnr.close();
}
}
public class MyLineNumberReader2 extends MyBufferedReader {
private Reader r;
private int lineNumber = 0;
public MyLineNumberReader2(Reader r) {
super(r);
}
public int getLineNumber() {
return lineNumber;
}
public void setLineNumber(int lineNumber) {
this.lineNumber = lineNumber;
}
@Override
public String readLine() throws IOException {
lineNumber++;
return super.readLine();
}
}