我是靠谱客的博主 健壮镜子,这篇文章主要介绍java读写文件,现在分享给大家,希望可以做个参考。

问题描述

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


程序如下:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

package com.read;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

public class MainTest {

public static void main(String[] args) throws Exception{
File f1 = new File("src/com/read/a.txt");
File f2 = new File("src/com/read/b.txt");

String str1 = readFile(f1);
String str2 = readFile(f2);
String [] strArray1 = str1.split(" ");
String [] strArray2 = str2.split("-| ");

FileWriter c = new FileWriter("src/com/read/c.txt");

int len1 = strArray1.length;
int len2 = strArray2.length;

boolean bool = len1>len2?true:false;
int i,j;
if(bool){
for(i=0;i<len2;i++){
c.write(strArray1[i]+" ");
c.write(strArray2[i]+" ");
}
for(int k =i;k<len1;k++){
c.write(strArray1[k]+" ");
}
}else{
for(j=0;j<len1;j++){
c.write(strArray1[j]+" ");
c.write(strArray2[j]+" ");
}
for(int k = j;k<len2;k++){
c.write(strArray2[k]+" ");
}
}
c.close();
}

public static String readFile(File file){
StringBuffer stringBuffer = new StringBuffer("");
BufferedReader reader = null;
try{
reader = new BufferedReader(new FileReader(file));
String tempStr = "";
while((tempStr=reader.readLine())!=null){
stringBuffer.append(tempStr);
}
}catch (Exception e) {
e.printStackTrace();
}
return stringBuffer.toString();
}
}



a.txt文件内容:
复制代码
1

1 2 3 4 55 67

b.txt文件内容:
复制代码
1

q w-2 3-3 4rt 5-y


输出的c.txt文件内容为:
复制代码
1

1 q 2 w 3 2 4 3 55 3 67 4rt 5 y

最后

以上就是健壮镜子最近收集整理的关于java读写文件的全部内容,更多相关java读写文件内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(56)

评论列表共有 0 条评论

立即
投稿
返回
顶部