qixun2016 2017-03-15 09:53 采纳率: 33.3%
浏览 8257
已采纳

编写一个Java程序将文件内容读出并显示到屏幕上

编写一个名为number1.txt的txt文档,内容包括100到109十个整数。编写一个Java程序将文件内容读出并显示到屏幕上,并以相反的顺序写入到文件number2.txt中。

  • 写回答

3条回答 默认 最新

  • 诚哥丿 2017-03-15 10:11
    关注

    package com.uf.test;

    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.Arrays;

    public class Home {

    public static void main(String[] args) {
    
        String inputFile = "C:\\Users\\wushucheng\\Desktop\\number1.txt";
        String outputFile = "C:\\Users\\wushucheng\\Desktop\\number2.txt";
        String content = getFileContent(inputFile);
        System.out.println(content);
    
        String[] array = content.split(" ");
        String[] newArray = new String[array.length];
        for (int i = 0; i < array.length; i++) {
            newArray[newArray.length - i - 1] = array[i];
        }
        String newContent = Arrays.toString(newArray).replaceAll("\\[|\\]", "");
        createFile(outputFile, newContent);
    }
    
    public static String getFileContent(String filePath){
    
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(filePath));
            StringBuffer stringBuffer = new StringBuffer();
            String temp = null;
            try {
                while((temp = reader.readLine()) != null){
                    stringBuffer.append(temp);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            return stringBuffer.toString();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally{
            if(reader != null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
        return null;
    }
    
    public static void createFile(String filePath, String content){
        PrintWriter writer = null;
        try {
            writer = new PrintWriter(new FileWriter(filePath));
            writer.write(content);
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            if(writer != null){
                writer.close();
            }
        }
    }
    

    }

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格