【发布时间】:2019-02-27 01:09:31
【问题描述】:
所以我试图从文本文件中读取输入,将其存储到变量中,然后使用文件中的变量将该文本的更改版本输出到不同的文件中。我正在使用 Filereader、Scanner 和 Printwriter 来执行此操作。 我必须存储此文本文档的最后一行(这是一个数字)并使用该数字将文本正文乘以不同的文件而不包括数字。
所以文本是: Original file text
输出应该是: desired output
我能够检索数字并将其存储到我的乘数变量中,并将文本检索到我的字符串中,但是如果我在控制台内部检查,它会存储为一行: how the text is stored seen through console
所以它在新文件上输出如下: undesired output
我是 Java 新手,如果有任何我无法回答的问题可以帮助解决我的代码中的任何问题,请原谅我。
我尝试将+"\n" 添加到文件输出行,但没有骰子。我还尝试将它添加到 words += keys.nextLine() +"\n",不幸的是,它分隔了 CONSOLE 中的行而不是文件本身。我至少在正确的轨道上吗?
这是我的代码:
public class fileRead {
public static void main(String[] args) throws IOException{
String words = "" ; //Stores the text from file
int multiplier = 1; // Stores the number
FileReader fr = new FileReader("hw3q3.txt");
Scanner keys = new Scanner(fr);
//while loop returns true if there is another line of text will repeat and store lines of text until the last line which is an int
while(keys.hasNextLine())
if (keys.hasNextInt()) { //validation that will read lines until it see's an integer and stores that number
multiplier = keys.nextInt(); //Stores the number from text
} else {
words += keys.nextLine();//Stores the lines of text
keys.nextLine();
}
keys.close();
PrintWriter outputFile = new PrintWriter("hw3q3x3.txt");
for(int i = 1; i <= multiplier; i++) {
outputFile.println(words);
}
outputFile.close();
System.out.println("Data Written");
System.out.println(multiplier);//just to see if it read the number
System.out.println(words); //too see what was stored in 'words'
}
}
【问题讨论】: