有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

按与新文件相反的顺序打印行

我试图编写一个程序,读取文件(“input.txt”)中的每一行,反转它的行,并将它们写入另一个文件(“output.txt”)

输入。txt文件内容如下:

How much wood could a woodchuck chuck  
If a woodchuck could chuck wood?  
As much wood as a woodchuck could chuck,  
If a woodchuck could chuck wood. 

当程序被执行时,输出。txt文件应为:

If a woodchuck could chuck wood. 
As much wood as a woodchuck could chuck,  
If a woodchuck could chuck wood?  
How much wood could a woodchuck chuck 

到目前为止,我使用的代码只会导致输出的第一行打印。txt文件。我不知道怎么把这四行都打印出来。谁能给我指出正确的方向吗


共 (1) 个答案

  1. # 1 楼答案

    要反转,只需在前面添加下一行。我已经更正了你的代码(见下文)。看看我在哪里添加了评论

    此外,你这样做的方式是不好的做法(我不知道这是否是你必须填写的样板代码)。你真的应该这样定义你的函数

    public static String ReadFile(String fileContents) throws...
    

    或者

    public static String ReadFile (Reader r) throws ...{
    }
    

    这样定义方法可以让您首先用Java硬编码测试用例,而不用担心IO部分。它还使该方法更加有用,因为读取器可以来自字符串读取器、套接字或文件


    public static String ReadFile(String filePath) throws FileNotFoundException 
    {
    
       File inputFile = new File (filePath);
       Scanner in = new Scanner (inputFile);
       String str = new String ("");
       while (in.hasNextLine())
       {
    //       str += in.nextLine(); //this is wrong
           str = in.nextLine() + "\n" + str;
       }
    
       in.close();
       return str; // this is all the text in the file. thats the purpose of this methods 
    
    }