栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java实现合并2个文件中的内容到新文件中

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java实现合并2个文件中的内容到新文件中

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

复制代码 代码如下:
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;

public class FileTest {
   
    //a.txt                                     //b.txt
   
    public static void main(String[] args) throws IOException {
        //读取a.txt b.txt里的内容 转为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;// a.txt里面所有的单词
        List bWords = Lists.newArrayList(Splitter.on(" ").split(Joiner.on(" ").join(bList)));// b.txt里面所有的单词
        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(" ");
        }
        // 写入文件
        String cpath = FileTest.class.getClassLoader().getResource("c.txt").getPath();
        File file = new File(cpath);
        Files.write(from, file, Charsets.UTF_8);
    }
}

以上代码就是本文的全部内容了,希望大家能够喜欢。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/151754.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号