Java 如何反转文本文件
我必须用java反转一段文字。例如,如果文本文件Java 如何反转文本文件,java,reverse,Java,Reverse,我必须用java反转一段文字。例如,如果文本文件 Hello world This is a example 运行java reverse input.txt output.txt,然后output.txt包含 This is a example Hello world 到目前为止,我的代码只读取输入。txt的标准方式。关于如何逆转的任何想法。我卡住了 import java.io.*; public class Test { public static void main(Str
Hello world
This is a example
运行java reverse input.txt output.txt,然后output.txt包含
This is a example
Hello world
到目前为止,我的代码只读取输入。txt的标准方式。关于如何逆转的任何想法。我卡住了
import java.io.*;
public class Test {
public static void main(String [] args) {
/**
* The name of the file and the location of the file.
*/
String fileName = "test.txt";
/**
* This will enter one line at a time
* FileReader reads text files
*/
String line = null;
try {
FileReader fileReader =
new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader =
new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
/**
* Closing the file.
*/
bufferedReader.close();
}
/**
*Telling the program what message to show if the file is not found
*/
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
}
}
}
可以使用字符串类型的堆栈。 读取文件时将字符串添加到堆栈:
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
myStack.Push(line);
}
并从堆栈末尾读取:
bufferedReader.close();
while(!myStack.isEmpty()){
System.out.println(myStack.Pop());
}
还有一些代码上的小改动。您可以使用递归:
//firt you need have a method by allowing it to call itself
void tac (){
/*local variable, change betweens calls because the language have his
own stack that use for make calls at the methods*/
String line;
//end condition;
if (line = bufferedReader.readLine()) != null){
//new instance of method
tac ();
//print the value of his local variable instance
System.out.println(line);
}
}
第一次调用使用line1并调用自身并创建新行->line2这可以继续。。。亚麻布
当得到最终条件时;按调用的相反顺序返回,他们打印此返回….,打印第2行此返回和打印第1行只需使用一个简单的字符串类型堆栈!我认为在编写代码之前先考虑现实世界中的问题会有所帮助。在一张纸上写一张单词表。试着颠倒单词的顺序,但只从上往下读。当你解决了这个问题后,很有可能你已经创建了类似于堆栈的东西。然后试着用Java重新创建这个过程。简单解释一下这个过程是如何工作的以及为什么工作的,可以让你的答案对未来的读者更有帮助。