The Java implementation merges the contents of two files into a new file

  • 2020-04-01 03:44:52
  • OfStack

Write a program that alternates the words in the a.xt file and the words in the b.xt file into the c.xt file. The words in the a.xt file are separated by carriage returns, and the words in the b.xt file are separated by carriage returns or Spaces.


package javase.arithmetic;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
import java.io.File;
import java.io.IOException;
import java.util.List;
/**
 * User: Realfighter
 * Date: 2015/3/10
 * Time: 18:06
 */
public class FileTest {
    /**
     * Write a program will a.txt The words in the document and b.txt The words in the file are alternately merged into c.txt In the file a.txt The words in the file are separated by carriage returns,
     * b.txt Files are separated by carriage returns or Spaces.
     */
    //a.txt                                     //b.txt
    /**
     i                                          this is a java program
     love                                       my name is Realfighter
     u
     baby
     */
    public static void main(String[] args) throws IOException {
        //Read the contents of a.t t b.t t to List
        String apath = FileTest.class.getClassLoader().getResource("a.txt").getPath();
        List aList = Files.readLines(new File(apath), Charsets.UTF_8);
        String bpath = FileTest.class.getClassLoader().getResource("b.txt").getPath();
        List bList = Files.readLines(new File(bpath), Charsets.UTF_8);
        List aWords = aList;//All the words in a. t.
        List bWords = Lists.newArrayList(Splitter.on(" ").split(Joiner.on(" ").join(bList)));//All the words in b.t.
        List bigOne = aWords.size() >= bWords.size() ? aWords : bWords;
        List smallOne = aWords.size() >= bWords.size() ? bWords : aWords;
        StringBuffer from = new StringBuffer();
        for (int i = 0; i < smallOne.size(); i++) {
            from.append(bigOne.get(i)).append(" ").append(smallOne.get(i)).append(" ");
        }
        for (int j = smallOne.size(); j < bigOne.size(); j++) {
            from.append(bigOne.get(j)).append(" ");
        }
        //Write to file
        String cpath = FileTest.class.getClassLoader().getResource("c.txt").getPath();
        File file = new File(cpath);
        Files.write(from, file, Charsets.UTF_8);
    }
}

That's all for this article, and I hope you enjoy it.


Related articles: