编写一个程序,将a.txt文件中的单词与b.txt文件中的单词交

2017-09-29  本文已影响0人  bug_华

主方法类:


packagecom.cdut;

importjava.io.FileWriter;

public classMain {

public static voidmain(String[] args)throwsException {

FileWriter ra =newFileWriter("a.text");

ra.write("a\nc\ne\ng\n");

ra.close();

FileWriter rb =newFileWriter("b.text");

rb.write("b\nd f h");

rb.close();

FileManager a =newFileManager("a.text",new char[]{'\n'});

FileManager b =newFileManager("b.text",new char[]{'\n',' '});

FileWriter rc =newFileWriter("c.text");

String aWord =null;

String bWord =null;

while((aWord=a.nextWord())!=null){

rc.write(aWord);

bWord = b.nextWord();

if(bWord !=null){

rc.write(bWord);

}

}

while((bWord=b.nextWord())!=null){

rc.write(bWord);

}

rc.close();

}

}

FileManager类:


packagecom.cdut;

importjava.io.File;

importjava.io.FileReader;

/**

* FileManager的作用:读取文件中的字符流,将启转换成String数组,并给出遍历方法:

*nextWord()

*/

public classFileManager {

String[]words=null;

intpos=0;//words的下标

//seperator为分隔符

publicFileManager(String fileName,char[] seperators)throwsException{

File file =newFile(fileName);

FileReader reader =newFileReader(file);

char[] buf =new char[(int)(file.length())];

intlen = reader.read(buf);

String result =newString(buf,0, len);

String regex =null;//正则表达式

if(seperators.length>1){

regex =""+seperators[0]+"|"+seperators[1];

}else{

regex =""+seperators[0];

}

words= result.split(regex);

reader.close();

}

publicString nextWord(){

if(pos==words.length){

return null;

}

returnwords[pos++];

}
}
上一篇下一篇

猜你喜欢

热点阅读