Home > Java > JavaBase > body text

How to write files in java

angryTom
Release: 2019-11-11 16:35:52
Original
5015 people have browsed it

How to write files in java

java怎么写文件

1、首先创建一个FileWriter对象;

2、然后使用FileWriter的write方法写入数据;

3、最后使用FileWriter的close方法关闭即可。

推荐教程:java教程

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
public class fileTest {
    public static void main(String[] args) {
        File file = new File("F:\\test.txt");
        if (!file.exists()) {
            try {
                file.createNewFile(); //如果文件不存在则创建文件
            } catch (IOException e) {
                e.printStackTrace();
            }  
        }
        writeInFile(file, "test");   //写入文件
    }
    
    private static void writeInFile(File file, String content) {
        Writer writer = null;
        StringBuilder outputString = new StringBuilder();
        try {
            outputString.append(content + "\r\n");
            writer = new FileWriter(file, true); // true表示追加
            writer.write(outputString.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                writer.close();
            } catch (IOException e2) {
                e2.printStackTrace();
            }
        }
    }
}
Copy after login

The above is the detailed content of How to write files in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!