[英]Reading int value from text file, and using value to alter file contents to separate text file.(java)
因此,我嘗試從文本文件讀取輸入,將其存儲到變量中,然后使用文件中的變量將文本的更改版本輸出到其他文件中。 我正在使用Filereader,Scanner和Printwriter來做到這一點。 我必須存儲此文本文檔的最后一行(是一個數字),並使用該數字將文本正文乘到另一個文件上,而不包括該數字。
所以文本是: 原始文件文本
並且輸出應該是: 所需的輸出
我能夠檢索數字並將其存儲在乘數變量中,並將文本檢索到字符串中,但是如果我在控制台內部檢查,它會以一行形式存儲 : 如何通過控制台查看文本的存儲方式
因此它在新文件上輸出如下: 不需要的輸出
我是Java的新手,如果有任何無法解決的問題可以原諒我,請原諒我。
我嘗試將+"\\n"
添加到文件輸出行,但沒有骰子。 我還嘗試將其添加到單詞+ = 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'
}
}
請參見下面的if語句:
words += keys.nextLine(); //Stores the lines of text
if(words.endsWith(words.substring(words.lastIndexOf(" ")+1))) { //detect last word in sentence
words += '\n'; //after last word, append newline
}
...
for(int i = 1; i <= multiplier; i++) {
outputFile.print(words); //change this to print instead of println
}
基本上,在文件中句子中的最后一個詞之后,我們要添加一個換行符以開始從換行中寫入下一個句子。
上述if語句通過確定最后一個字內檢測到句子的結尾words
字符串,然后追加一個換行符的words
字符串。 這將產生您期望的結果。
為您分解表達式:
words.substring(words.lastIndexOf(" ")+1)
返回位於substring
最后一個空格索引處的String( substring
)部分加1( lastIndexOf(" ") + 1
)-即,我們在最后一個空格之后得到單詞,因此最后一個單詞。
整個while循環:
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
if(words.endsWith(words.substring(words.lastIndexOf(" ")+1))) {
words += '\n';
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.