package cn.test.may;
import java.io.File;
import java.io.FileReader;
public class FileManager {
String words[] = null;
int pos = 0;
public FileManager(String filename, char[] seperators) throws Exception {
//文件全部读出变成字符串
File file = new File(filename);
FileReader fr = new FileReader(file);
char[] buf = new char[(int) file.length()];
int len = fr.read(buf);
String results = new String(buf, 0, len);
fr.close();
//按需求分割成数组
String regex = null;
if (seperators.length > 1) {
regex = seperators[0] + "|" +seperators[1];
} else {
regex = seperators[0] + "";
}
words = results.split(regex);
}
//可以将分割好的字符一个个读出
public String nextWord() {
if (pos == words.length)
return null;
return words[pos++];
}
}
上面接受文件的类,下面执行
package cn.test.may;
import java.io.FileWriter;
/*
* 编写一个程序,将a.txt文件中的单词
* 与b.txt文件中的单词交替合并到c.txt文件中,
* a.txt文件中的单词用回车符分隔,
* b.txt文件中用回车或空格进行分隔。
*/
public class Test1 {
public static void main(String[] args) throws Exception {
FileManager a = new FileManager("C:\\Users\\Administrator\\Desktop\\test\\a.txt", new char[]{'\n'});
FileManager b = new FileManager("C:\\Users\\Administrator\\Desktop\\test\\b.txt", new char[]{'\n',' '});
FileWriter fw = new FileWriter("C:\\Users\\Administrator\\Desktop\\test\\c.txt");
String aw = null;
String bw = null;
while ((aw = a.nextWord()) != null) {
fw.write(aw + "\n");
bw = b.nextWord();
if (bw != null) {
fw.write(bw + "\n");
}
}
while ((bw = b.nextWord()) != null) {
fw.write(bw + "\n");
}
fw.close();
}
}