Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何替换text file.java中的特定行_Java - Fatal编程技术网

如何替换text file.java中的特定行

如何替换text file.java中的特定行,java,Java,基本上,我正在编写一个程序,该程序需要能够通过循环每一行并进行比较来替换特定的文本行,或者能够获取行号,然后用新文本替换它(最好是第二种解决方案)。 假设我有一个文本文件 the sky is blue 我想用海洋来代替天空这个词。我可以说loop-through并找到值为sky的单词,或者我可以指定要替换的行位于第2行,然后像这样替换它。无论哪种方式,解决方案都应该是 the ocean is blue 我不知道该怎么做。非常感谢您的帮助。创建并打开文件流。然后,在循环中,逐行读取并写入使

基本上,我正在编写一个程序,该程序需要能够通过循环每一行并进行比较来替换特定的文本行,或者能够获取行号,然后用新文本替换它(最好是第二种解决方案)。 假设我有一个文本文件

the
sky
is
blue
我想用海洋来代替天空这个词。我可以说loop-through并找到值为sky的单词,或者我可以指定要替换的行位于第2行,然后像这样替换它。无论哪种方式,解决方案都应该是

the
ocean
is
blue

我不知道该怎么做。非常感谢您的帮助。

创建并打开文件流。然后,在循环中,逐行读取并写入使用另一个流创建的新文件,当循环计数器变量等于所需的行号时,然后写入新行而不是该行,让循环完成。最后,关闭两条流。请记住,第一行不是1,而是0。请记住,必须循环到文件末尾,必须独立维护循环变量,这意味着您不能使用for循环,而是使用while循环。

读取文件并替换所需的单词

     public static void main(String[] args) throws IOException {
        File file = new File("file.txt");
        BufferedReader reader = new BufferedReader(new FileReader(file));

        String words = "", list = "";

        while ((words = reader.readLine()) != null) {
            list += words + "\r\n";
        }
        reader.close();

        String replacedtext = list.replaceAll("sky", "" + "ocean");

        FileWriter writer = new FileWriter("file.txt");
        writer.write(replacedtext);
        writer.close();

    }
}

逐行读取文件,输出到临时文件,完成后重命名文件副本