Java 使用 Scanner 类在文本文件中写入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36931603/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 18:50:50  来源:igfitidea点击:

Writing Inside a text file using Scanner Class

javafilejava.util.scanner

提问by Vinay Verma

I have Come across so many programmes of how to read a text file using Scannerin Java. Following is some dummy code of Reading a text file in Java using Scanner:

我遇到过很多关于如何使用ScannerJava读取文本文件的程序。以下是使用 Java 读取文本文件的一些虚拟代码Scanner

public static void main(String[] args) {

    File file = new File("10_Random");

    try {

        Scanner sc = new Scanner(file);

        while (sc.hasNextLine()) {
            int i = sc.nextInt();
            System.out.println(i);
        }
        sc.close();
    } 
    catch (FileNotFoundException e) {
        e.printStackTrace();
    }
 }

But, please anyone help me in "Writing" some text (i.e. String or Integer type text) inside a .txtfile using Scannerin java. I don't know how to write that code.

但是,请任何人帮助我在 java 中.txt使用的文件中“写入”一些文本(即字符串或整数类型的文本)Scanner。我不知道如何编写该代码。

回答by Sanjeev

Scanneris for reading purposes. You can use Writerclass to write data to a file.

Scanner是为了阅读。您可以使用Writer类将数据写入文件。

For Example:

例如:

Writer wr = new FileWriter("file name.txt");
wr.write(String.valueOf(2))  // write int
wr.write("Name"); // write string

wr.flush();
wr.close();

Hope this helps

希望这可以帮助

回答by jamesomahony

Scannercan't be used for writing purposes, only reading. I like to use a BufferedWriterto write to text files.

Scanner不能用于写作目的,只能用于阅读。我喜欢使用 aBufferedWriter写入文本文件。

BufferedWriter out = new BufferedWriter(new FileWriter(file));
out.write("Write the string to text file");
out.newLine();