您的位置:首页 > 其它

编写一个程序,将 a.txt文件中的单词与b.txt文件中的单词交替合并到c.txt 文件中,a.txt文件中的单词用回车符分隔,b.txt文件中用回车或空格进行分隔

2015-07-14 14:45 645 查看
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class newManagerFile {
String words[];
int pos = 0;

public newManagerFile(String fileName, char spilt[]) 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 bufString = new String(buf, 0, len);
StringBuffer temp = new StringBuffer("");
temp.append(spilt[0]);
if (spilt.length > 1) {
int posl = 2;
while (posl <= spilt.length) {
temp.append("|");
temp.append(spilt[posl - 1]);
posl++;
}
}
String bs = temp.toString();
words = bufString.split(bs);
}

public String nextWord() {
if (pos == words.length) {
return null;
} else {
return words[pos++];
}

}

public static void main(String[] args) throws Exception {
newManagerFile a = new newManagerFile("G:\\a.txt", new char[] { '\n' });
newManagerFile b = new newManagerFile("G:\\b.txt", new char[] { '\n',
' ' });
FileWriter c = new FileWriter("G:\\c.txt");
String aWord = null;
String bWord = null;
while ((aWord = a.nextWord()) != null) {
c.write(aWord);
bWord = b.nextWord();
if (bWord != null) {
c.write(bWord);
}
}
if (bWord != null) {
c.write(bWord);
}
c.close();
System.out.println("finish");
}
}


主要对文件读写的考察,自己一开始编写的可读性不好,借鉴了一下已有的代码进行了优化,这里建议不要过多使用string而是用stringbuffer,while语句这里的条件是比较优化的一点
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: