(1)把集合中的資料存儲到文本檔案
* 需求:把ArrayList集合中的字元串資料存儲到文本檔案
*
* 分析:
* 通過題目的意思我們可以知道如下的一些内容,
* ArrayList集合裡存儲的是字元串。
* 周遊ArrayList集合,把資料擷取到。
* 然後存儲到文本檔案中。
* 文本檔案說明使用字元流。
*
* 資料源:
* ArrayList<String> -- 周遊得到每一個字元串資料
* 目的地:
* a.txt -- FileWriter -- BufferedWriter
package cn.itcast_02;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
/*
* 需求:把ArrayList集合中的字元串資料存儲到文本檔案
*
* 分析:
* 通過題目的意思我們可以知道如下的一些内容,
* ArrayList集合裡存儲的是字元串。
* 周遊ArrayList集合,把資料擷取到。
* 然後存儲到文本檔案中。
* 文本檔案說明使用字元流。
*
* 資料源:
* ArrayList<String> -- 周遊得到每一個字元串資料
* 目的地:
* a.txt -- FileWriter -- BufferedWriter
*/
public class ArrayListToFileDemo {
public static void main(String[] args) throws IOException {
// 封裝資料與(建立集合對象)
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) {
// 寫資料
bw.write(s);
bw.newLine();
bw.flush();
}
// 釋放資源
bw.close();
}
}
(2)把文本檔案中的資料讀取到集合中并周遊集合
* 需求:從文本檔案中讀取資料(每一行為一個字元串資料)到集合中,并周遊集合
*
* 分析:
* 通過題目的意思我們可以知道如下的一些内容,
* 資料源是一個文本檔案。
* 目的地是一個集合。
* 而且元素是字元串。
*
* 資料源:
* b.txt -- FileReader -- BufferedReader
* 目的地:
* ArrayList<String>
package cn.itcast_02;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
/*
* 需求:從文本檔案中讀取資料(每一行為一個字元串資料)到集合中,并周遊集合
*
* 分析:
* 通過題目的意思我們可以知道如下的一些内容,
* 資料源是一個文本檔案。
* 目的地是一個集合。
* 而且元素是字元串。
*
* 資料源:
* b.txt -- FileReader -- BufferedReader
* 目的地:
* ArrayList<String>
*/
public class FileToArrayListDemo {
public static void main(String[] args) throws IOException {
// 封裝資料源
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();
// 周遊集合
for (String s : array) {
System.out.println(s);
}
}
}