java 实现将a.txt和b.txt中的文件交替存放在c.txt文件中
要求:将a.txt 和b.txt中的文件交替放置在c.txt 文件中,其中a.txt和b.txt文件中的文字以空格或者回车将其分开
public class MainClass { public static void main(String[] args) throws Exception { FileManager a = new FileManager("d:\\a.txt"," "); FileManager b = new FileManager("d:\\b.txt"," |\n"); FileWriter c = new FileWriter("d:\\c.txt"); String aWord = null; String bWord = null; while((aWord =a.nextWord())!=null&&(bWord= b.nextWord())!=null) { c.write(aWord + "\n"); c.write(bWord); c.write("\n"); } while((aWord =a.nextWord())==null&&(bWord= b.nextWord())!=null) { c.write(bWord); c.write("\n"); } while((bWord= b.nextWord())==null&&(aWord =a.nextWord())!=null) { c.write(aWord + "\n"); } c.close(); } }
class FileManager {
String[] words = null;
int pos = 0;
public FileManager(String fileName,String seperators) throws Exception {
File file = new File(fileName);
Reader reader = new FileReader(file);
char[] buffer = new char[(int)file.length()];
reader.read(buffer);
String result = new String(buffer,0,buffer.length);
words = result.split(seperators);
}
public String nextWord(){
if(pos == words.length-1)
return null;
return words[pos++];
}
}
public class MainClass { public static void main(String[] args) throws Exception { FileManager a = new FileManager("d:\\a.txt"," "); FileManager b = new FileManager("d:\\b.txt"," |\n"); FileWriter c = new FileWriter("d:\\c.txt"); String aWord = null; String bWord = null; while((aWord =a.nextWord())!=null&&(bWord= b.nextWord())!=null) { c.write(aWord + "\n"); c.write(bWord); c.write("\n"); } while((aWord =a.nextWord())==null&&(bWord= b.nextWord())!=null) { c.write(bWord); c.write("\n"); } while((bWord= b.nextWord())==null&&(aWord =a.nextWord())!=null) { c.write(aWord + "\n"); } c.close(); } }
class FileManager {
String[] words = null;
int pos = 0;
public FileManager(String fileName,String seperators) throws Exception {
File file = new File(fileName);
Reader reader = new FileReader(file);
char[] buffer = new char[(int)file.length()];
reader.read(buffer);
String result = new String(buffer,0,buffer.length);
words = result.split(seperators);
}
public String nextWord(){
if(pos == words.length-1)
return null;
return words[pos++];
}
}