Home >Java >JavaBase >How to write files in java

How to write files in java

angryTom
angryTomOriginal
2019-11-11 16:35:525082browse

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();
            }
        }
    }
}

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!

Statement:
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

Related articles

See more