题目是这样的:
编写一个程序,将a.txt文件中的单词与b.txt文件中的单词交替合并到c.txt文件中,a.txt文件中的单词用回车符分隔,b.txt文件中用回车或空格进行分隔。
大概想了一下,先实现功能,有时间再看看优化一下。
package IoStreamTest;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class IoStreamTest {
public static void main(String[] args) {
File a = new File("D:/a.txt");
File b = new File("D:/b.txt");
char[] Achars = new char[(int) a.length()];
char[] Bchars = new char[(int) b.length()];
try {
if (a.canRead()) {
FileReader fr = new FileReader(a);
int read = fr.read(Achars);
}
if (b.canRead()) {
FileReader fileReader = new FileReader(b);
int read = fileReader.read(Bchars);
}
String[] strings = new IoStreamTest().dealChars(Achars);
String[] strings1 = new IoStreamTest().dealChars(Bchars);
int lengthA = strings.length;
int lengthB = strings1.length;
int max = Integer.max(lengthA, lengthB);
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < max; i++) {
if (i < lengthA) {
stringBuilder.append(strings[i]);
}
if (i < lengthB) {
stringBuilder.append(strings1[i]);
}
}
File file = new File("D:/c.txt");
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(stringBuilder.toString());
fileWriter.close();
System.out.println("完成");
} catch (Exception e) {
}
}
/**
* 把传入的字符数组,通过处理删除字符数组中的回车、空格,转换成字符串数组并输出。
* @param c
* @return
*/
public String[] dealChars(char[] c) {
String[] s = null;
if (null == c) {
s = new String[1];
s[1] = "null";
return s;
} else {
List<String> list = new ArrayList<String>();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < c.length; i++) {
if ("\n".equals(String.valueOf(c[i])) || "\r".equals(String.valueOf(c[i])) || " ".equals(String.valueOf(c[i]))) {
list.add(stringBuilder.toString());
stringBuilder.setLength(0);
} else {
stringBuilder.append(c[i]);
if (i == c.length - 1) {
list.add(stringBuilder.toString());
}
}
}
for (int i = 0; i < list.size(); i++) {
if ("".equals(list.get(i))) {
list.remove(i);
}
}
s = new String[list.size()];
for (int i = 0; i < s.length; i++) {
s[i] = list.get(i);
}
return s;
}
}
}