如何在 Java 中编辑 .txt 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2818207/
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
How to edit a .txt file in Java
提问by mASOUD
i think i can use "Scanner" to read a .txt file but how can i write or even create a new text file?
我想我可以使用“扫描仪”来读取 .txt 文件,但是我如何编写甚至创建一个新的文本文件?
采纳答案by rgksugan
To create a new text file
创建新的文本文件
FileOutputStream object=new FileOutputStream("a.txt",true);
object.write(byte[]);
object.close();
This will create a file if not available and if a file is already available it will append data to it.
如果不可用,这将创建一个文件,如果文件已经可用,它将向其附加数据。
回答by npinti
This Basic I/O and Files Tutorialshould do the trick :)
这个基本 I/O 和文件教程应该可以解决问题:)
回答by ZeissS
Create a java.io.FileOutputStream to write it. To write text, you can create a PrintWriteraround it.
创建一个 java.io.FileOutputStream 来编写它。要编写文本,您可以PrintWriter围绕它创建一个。
回答by ramayac
This simple code example will create the text file if it doesn't exist, and if it does, it will overwrite it:
如果文本文件不存在,这个简单的代码示例将创建它,如果存在,它将覆盖它:
try {
FileWriter outFile = new FileWriter("c:/myfile.txt");
PrintWriter out = new PrintWriter(outFile);
// Also could be written as follows on one line
// Printwriter out = new PrintWriter(new FileWriter(filename));
// Write text to file
out.println("This is some text I wrote");
out.close();
} catch (IOException e) {
e.printStackTrace();
}
Hope it helps!
希望能帮助到你!

