1. 程式人生 > >,編寫一個程式,將a.txt檔案中的單詞與b.txt檔案中的單詞交替合併到c.txt檔案中,a.txt檔案中的單詞用回車符分隔,b.txt檔案中用回車或空格進行分隔.

,編寫一個程式,將a.txt檔案中的單詞與b.txt檔案中的單詞交替合併到c.txt檔案中,a.txt檔案中的單詞用回車符分隔,b.txt檔案中用回車或空格進行分隔.

在java面試寶典看到這樣一題,看到答案真蛋疼,看了半天才明白,可能每個人的想法不一樣!答案也不知道是那位前輩寫的,讓人理解起來太費精了!老饒彎子,以下是本人自已整理的,去面試如果真有這麼一題,應該不成問題了。。。。。。。如有不是的地方還望指點


package accp.readWriterFile;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class MainClass{
public static void main(String[] args) throws Exception{

//讀 引數1:檔名, 引數1:我要掃照什麼格式進行拆分
String[] aWord=MainClass.read("a.txt", " ");
String[] bWord=MainClass.read("b.txt"," ");

//ab檔案的組合陣列
String [] ab=new String[aWord.length+bWord.length];

//得到最大的那個陣列長度
int ii=0;
int coutn =(ii=aWord.length)>bWord.length?ii:bWord.length;

//開始組合陣列 到一個新的陣列  就是你一個我一個交差組合
int j=0;
for(int i=0;i<coutn;i++){
//如果陣列索引比i大就說明還有資料
if(aWord.length>i){
ab[j]=aWord[i]+"\n"; //加回車
j++;
}
//如果陣列索引比i大就說明還有資料
if(bWord.length>i){
  ab[j]=bWord[i]+"\n"; //加空格或回車
  j++;
}

}


//寫入到c.txt檔案中
FileWriter c= new FileWriter("c.txt");
MainClass.writers(c, ab);
c.close();
}

//讀
public static String[]  read(String filename, String regex) throws IOException{

File f = new File(filename);
FileReader reader = new FileReader(f);

char[] buf =new char[(int)f.length()];
reader.read(buf); //讀取所有的字元到buf數組裡

String results = new String(buf);//轉換在字串

return results.split(regex);//拆分並反回附合需求的字串組數

}

//寫
public static void writers(FileWriter c,String[] words){

for(int i=0;i<words.length;i++){
try {
c.write(words[i]+" ");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

}