java实现合并2个文件中的内容到新文件中
时间:2021-10-19 08:56:53|栏目:JAVA代码|点击: 次
编写一个程序 将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;
/**
* User: Realfighter
* Date: 2015/3/10
* Time: 18:06
*/
public class FileTest {
/**
* 编写一个程序 将a.txt文件中的单词与b.txt文件中的单词交替合并到c.txt文件中 a.txt文件中的单词用回车符分隔,
* b.txt文件中用回车或空格进行分隔。
*/
//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 {
//读取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);
}
}
以上代码就是本文的全部内容了,希望大家能够喜欢。


阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机




