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
Writing Inside a text file using Scanner Class
提问by Vinay Verma
I have Come across so many programmes of how to read a text file using Scanner
in Java. Following is some dummy code of Reading a text file in Java using Scanner
:
我遇到过很多关于如何使用Scanner
Java读取文本文件的程序。以下是使用 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 .txt
file using Scanner
in java. I don't know how to write that code.
但是,请任何人帮助我在 java 中.txt
使用的文件中“写入”一些文本(即字符串或整数类型的文本)Scanner
。我不知道如何编写该代码。
回答by Sanjeev
Scanner
is for reading purposes. You can use Writer
class 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
Scanner
can't be used for writing purposes, only reading. I like to use a BufferedWriter
to write to text files.
Scanner
不能用于写作目的,只能用于阅读。我喜欢使用 aBufferedWriter
写入文本文件。
BufferedWriter out = new BufferedWriter(new FileWriter(file));
out.write("Write the string to text file");
out.newLine();