编写一个程序,把text1.txt中的单词与text2.txt中的单词交互保存到text3.txt中,单词用空格或回车分割:
public class FileManager {
String[] word=null;
int pos = 0;
public FileManager(String filename,char[] sep) throws IOException {
File file = new File(filename);
@SuppressWarnings("resource")
FileReader fr = new FileReader(file);
char[] c = new char[(int) file.length()];
int len = fr.read(c);
String result = new String(c, 0, len);
String rex = "";
if(sep.length>1) {
rex = "" + sep[0]+"|"+sep[1];
}else {
rex = ""+sep[0];
}
word = result.split(rex);
}
public String nextWord() {
if(pos==word.length) {
return null;
}else {
return word[pos++];
}
}
}
测试类:
public static void main(String[] args) throws IOException {
FileManager t1 = new FileManager("D:\\ThreeWord\\text1.txt", new char[] {'\n'});
FileManager t2 = new FileManager("D:\\ThreeWord\\text2.txt", new char[] {'\n',' '});
FileWriter t3 = new FileWriter("D:\\ThreeWord\\text3.txt");
String t1word = null;
String t2word = null;
while((t1word = t1.nextWord()) != null) {
t3.write(t1word+"\n");
t2word = t2.nextWord();
if(t2word != null) {
t3.write(t2word+"\n");
}
}
while((t2word = t2.nextWord())!= null) {
t3.write(t2word+"\n");
}
t3.close();
}
效果: