THE ONE
定义一个集合,向集合中添加一些字符串,然后将集合中的所有字符串内容写到文件中,每个字符串占一行。
分析:
1, 定义一个集合ArrayList,
2. add添加字符串
3. 定义字符流缓冲对象 BufferedWriter
4. 循环遍历集合写入文件,注意换行
代码:
public static void main(String[] args) throws IOException {
ArrayList<String> arrayList=new ArrayList<String>();
arrayList.add("1:你好");
arrayList.add("2:你不好");
arrayList.add("3:你非常不好");
BufferedWriter bw=new BufferedWriter(new FileWriter("test1.txt"));
for (String arr : arrayList) {
bw.write(arr);
bw.newLine();
}
bw.close();
}
THE TWO
将文件中的字符串文本读取到集合当中,并且每一行文本作为集合中的一个元素
代码:
public static void main(String[] args) throws IOException {
FileReader fr=new FileReader("test1.txt");
BufferedReader bfr=new BufferedReader(fr);
String line;
ArrayList<String> arrayList =new ArrayList<String>();
while ((line=bfr.readLine())!=null) {
arrayList.add(line);
}
for (String string : arrayList) {
System.out.println(string);
}
}
THE THREE
将一个文本文档上的文本反转,第一行和倒数第一行交换,第二行和倒数第二行交换
分析:
1,创建输入输出流对象
2,创建集合对象
3,将读到的数据存储在集合中
4,倒着遍历集合将数据写到文件上
5,关流
代码:
public static void main(String[] args) throws IOException {
ArrayList<String > arrayList=new ArrayList<String>();
FileReader fr=new FileReader("test1.txt");
BufferedReader bfr=new BufferedReader(fr);
String line;
FileWriter fw=new FileWriter("test3.txt");
BufferedWriter bfw=new BufferedWriter(fw);
while ((line=bfr.readLine())!=null) {
arrayList.add(line);
}
for (int i = arrayList.size()-1;i>=0; i--) {
String line1=arrayList.get(i);
bfw.write(line1);
bfw.newLine();
}
bfw.close();
bfr.close();