gpt4 book ai didi

java - 以相反的顺序将行打印到新文件 java

转载 作者:行者123 更新时间:2023-12-02 09:07:56 25 4
gpt4 key购买 nike

我正在尝试编写一个程序,该程序读取文件(“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 行。有人能指出我正确的方向吗?

最佳答案

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

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

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

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

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

<小时/>
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

}

关于java - 以相反的顺序将行打印到新文件 java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59653995/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com