面试题1

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package com.maoge;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class {
public static void main(String []args)throws IOException{
char[] ca = new char[]{'n'};
char[] cb = new char[]{'n',' '};
FileManager a = new FileManager("D:\IDEA\workspace\file\a.txt",ca);
FileManager b = new FileManager("D:\IDEA\workspace\file\b.txt",cb);
FileWriter fw = new FileWriter("D:\IDEA\workspace\file\c.txt");
String aword = null;
String bword = null;
while ((aword=a.nextWord())!=null){
fw.write(aword+"n");

if ((bword=b.nextWord())!=null){
fw.write(bword+"n");
}
}

while ((bword=b.nextWord())!=null){
fw.write(bword+"n");
}

fw.close();
}

static class FileManager{
String words[] = null;
int position = 0;

public FileManager(String f, char[] c)throws IOException {
File file = new File(f);
FileReader reader = new FileReader(file);
char[] buf = new char[(int)file.length()];
int len = reader.read(buf);
String result = new String(buf,0,len);

String regex = null;
if(c.length==1){
regex = ""+c[0];
}else {
regex = ""+c[0]+"|"+c[1];
}

words = result.split(regex);
}

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

}

}

limaodeng

scribble