zoukankan      html  css  js  c++  java
  • Java第三次作业第四题

    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. 目录结构:

  • 相关阅读:
    Flutter DraggableScrollableSheet 可滚动对象的容器
    Flutter 避免阻塞ui线程
    Android Kotlin 数据驱动模板
    ng mock服务器数据
    rxjs 常用的subject
    Flutter 在同一页面显示List和Grid
    dart2native 使用Dart 在macOS,Windows或Linux上创建命令行工具
    Flutter 创建透明的路由页面
    ng 发布组件库
    js实现单张或多张图片持续无缝滚动
  • 原文地址:https://www.cnblogs.com/zqm-sau/p/10331780.html
Copyright © 2011-2022 走看看