4. 【问题描述】读取一个文本文件in.txt,然后将这个文件的内容,反序写到另一个文件out.txt中。
【输入形式】从文件in.txt中读信息。###
【输出形式】反序内容写入out.txt文件中。###
【样例输入】###
is worth doing well
【样例输出】###
well doing worth is
【样例说明】###
【评分标准】###
package naizi;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test {
public static void rwFile(){
FileWriter fw = null;
BufferedReader br = null;
try {
File file = new File("out.txt");
if(file.exists()){
file.delete();
}
br = new BufferedReader(new InputStreamReader(new FileInputStream("in.txt")));
fw = new FileWriter("out.txt", true);
String line = null;
while ((line = br.readLine()) != null) {
String[] arr = line.split(" "); //按空格分割
int length = arr.length; //计算数组长度
StringBuilder sb = new StringBuilder(line.length()); //新建一个StringBuilder对象
for (int i=length-1;i>=1;i--){
sb.append(arr[i]+" "); //将字符串依次加入StringBuilder中
}
sb.append(arr[0]); //最后一个单词不加空格
fw.write(sb.toString());
fw.flush();
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
rwFile();
}
}
运行结果如图:
1. in.txt
2. out.txt
3. 目录结构: