简体   繁体   English

如何在Java中编辑.txt文件

[英]How to edit a .txt file in Java

我认为我可以使用“扫描仪”读取.txt文件,但是如何编写甚至创建新的文本文件?

这个基本的I / O和文件教程应该可以解决问题:)

Create a java.io.FileOutputStream to write it. 创建一个java.io.FileOutputStream来编写它。 To write text, you can create a PrintWriter around it. 要编写文本,您可以在其周围创建一个PrintWriter

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. 如果不可用,这将创建一个文件,如果文件已经可用,它将向其添加数据。

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! 希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM