编程一

来源:互联网 发布:匿名者专用黑页源码 编辑:程序博客网 时间:2024/06/13 09:12

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

//首先,新建一个文件Txt,其中包含 a.txt、b.txt、c.txt
这里写图片描述

package com.test1;import java.io.FileWriter;/* * 编写程序,将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("./Txt/a.txt", new char[] { '\n' });        FileManager b = new FileManager("./Txt/b.txt", new char[] { '\n', ' ' });        FileWriter c = new FileWriter("./Txt/c.txt");        String aWord = null;        String bWord = null;        while ((aWord = a.nextWord()) != null) {            c.write(aWord + "\n");            bWord = b.nextWord();            if (bWord != null) {                c.write(bWord + "\n");            }            c.close();        }    }}
package com.test1;import java.io.File;import java.io.FileReader;public class FileManager {    String[] words = null;    int pos = 0;    public FileManager(String filename, char[] seperators) throws Exception {        File f = new File(filename);        FileReader fileReader = new FileReader(f);        char[] buf = new char[(int) f.length()]; // f.length 获取文件的大小 并用int强制转换        int len = fileReader.read(buf);        String results = new String(buf, 0, len);        String regex = null;        if (seperators.length > 1) {            regex = "" + seperators[0] + "|" + seperators[1];        } else {            regex = "" + seperators[0];        }        words = results.split(regex);    }    public String nextWord() {        if (pos == words.length)            return null;        return words[pos++];    }}
0 0
原创粉丝点击