简体   繁体   中英

How to edit a .txt file in Java

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

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

Create a java.io.FileOutputStream to write it. To write text, you can create a PrintWriter around it.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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