Java File Creation and Writing Guide

To create a file and write data in Java, you can use the FileOutputStream class. Here is a simple example code:

import java.io.FileOutputStream;
import java.io.IOException;

public class CreateFileExample {
    public static void main(String[] args) {
        try {
            // 创建文件输出流对象,指定文件路径
            FileOutputStream fos = new FileOutputStream("example.txt");

            // 要写入的数据
            String data = "Hello, World!";

            // 将数据转换为字节数组,并写入文件
            fos.write(data.getBytes());

            // 关闭文件输出流
            fos.close();

            System.out.println("文件创建并写入完成!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

After running the above code, a file named example.txt will be created in the current directory, and the string “Hello, World!” will be written to the file.

bannerAds