首页 > 解决方案 > 以相反的顺序将行打印到新文件java

问题描述

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

input.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. 

当程序执行时, output.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 

到目前为止,我的代码仅导致第一行打印到 output.txt 文件。我不知道如何打印所有 4 行。谁能指出我正确的方向?

标签: java

解决方案


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

此外,您这样做的方式是不好的做法(我不知道这是否是您必须填写的样板代码)。老实说,您应该定义您的功能,例如

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

或者

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

像这样定义你的方法可以让你首先用 Java 硬编码一个测试用例,而不用担心 IO 部分。它还使该方法更有用,因为 Reader 可以来自 String 读取器、Socket 或文件。


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 

} 

推荐阅读