黑马程序员---------通过流对文本文件进行修改
------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------
/**
* 求:
①将text1文件中的每一行倒序排列输出到text3中。比如:第一行是:a b c d e 处理后第一行是:e d c b a。
②找出text1和text2中不同的字符,并把这些字符输出到text4文件中,要求每5个字符换行一次,字符之间用空格分开。
*分析:每一行倒序,则使用ReadLine();然后切割,再转为字符数组再存储到text3
*判断 不同字符,输入时用for循环,到5,则换行,这些操作都涉及到了IO流,因为是有行操作,使用BufferedReader的readLine()就可以。
*/
<span style="font-size:18px;">import java.io.*;
import java.util.*;
public class Test29 {
public static void main(String[] args) throws IOException {
daoXu();
findDifferent();
show("text1.txt");
show("text2.txt");
show("text3.txt");
show("text4.txt");
}
public static void daoXu() throws IOException//倒序存储到text3
{
//操作文本,则使用字符流
BufferedReader fr = new BufferedReader(new FileReader("text1.txt"));
BufferedWriter fw = new BufferedWriter(new FileWriter("text3.txt"));//不能用True 因为会重复写
String str;
while((str=fr.readLine())!=null)
{
String[] str1 = str.split(" ");//根据空格切割
for(int x=str1.length-1;x>=0;x--)
{
fw.write(str1[x]+" ");
fw.flush();
}
fw.newLine();
fw.flush();
}
fw.close();
fr.close();
}
public static void findDifferent()throws IOException//查找不同点存储
{
//BufferedReader fr2 = new BufferedReader(new FileReader("text2.txt"));
//BufferedReader fr = new BufferedReader(new FileReader("text1.txt"));
BufferedWriter fw = new BufferedWriter(new FileWriter("text4.txt"));//不能用True 因为会重复写
//使用集合,取不同点,然后再把值写入文件
List<String> list1= getList("text1.txt");
List<String> list2= getList("text2.txt");
list1.removeAll(list2);//只留不同的值在集合当中
Iterator<String> it =list1.iterator();
int x=0;
while(it.hasNext())
{
String str =it.next();
fw.write(str+" ");
x++;
if(x==5)
{
fw.newLine();
}
fw.flush();
}
fw.close();
}
public static List<String> getList(String str) throws IOException
{
List<String> list = new ArrayList<String>();
BufferedReader fr = new BufferedReader(new FileReader(str));//将路径传入
String line;
while((line=fr.readLine())!=null)
{
String[] st = line.split(" ");//空格切割
for(int x=0;x<st.length;x++)
{
list.add(st[x]);//将字符存入集合
}
}
fr.close();
return list;
}
public static void show(String str)throws IOException
{
FileReader fr = new FileReader(str);
BufferedReader fr1 = new BufferedReader(fr);//可以使用readline
String str1;
System.out.println(str+"文件内容为:");
while((str1 = fr1.readLine())!=null)
{
System.out.println(str1);
}
fr1.close();
}}</span>