从文本文件中读取int值,并使用value将文件内容更改为单独的文本文件。(java)

问题描述 投票:1回答:1

所以我试图从文本文件中读取输入,将其存储到变量中,然后使用文件中的变量将该文本的更改版本输出到不同的文件中。我正在使用Filereader,Scanner和Printwriter来做到这一点。我必须存储此文本文档中的最后一行(这是一个数字),并使用该数字将文本正文乘以不包含数字的不同文件。

所以文本是:Original file text

输出是支持:desired output

我能够检索数字并将其存储到我的乘数变量中并将文本检索到我的字符串中但是如果我在控制台内检查它将存储为单行:how the text is stored seen through console

所以它在新文件中输出如下:undesired output

我是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'
}

}

java file loops text
1个回答
0
投票

请参阅下面的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加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';
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.