write to text file DEMO

本文介绍如何使用Java的FileWriter类进行文件写入操作,包括创建文件、写入内容及关闭资源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package HeadFirstJava;

import java.io.*;

class WriteFile {
    public static void main(String[] args) {
        try {
            FileWriter writer = new FileWriter("Foo.txt");
            writer.write("hello foo!");
            writer.close();
        } catch(IOException ex) {
            ex.printStackTrace();
        }
    }
}

### C++ 中 `ofstream` 的使用示例 在 C++ 中,`ofstream` 是用于文件输出的标准库类之一。下面展示如何创建并操作一个简单的文本文件以及二进制文件。 #### 创建和写入文本文件 ```cpp #include <iostream> #include <fstream> // Required for file stream operations [^3] int main() { std::ofstream outFile; outFile.open("example.txt"); // Open a text file named "example.txt" if (outFile.is_open()) { // Check whether the file was successfully opened outFile << "This is an example line.\n"; outFile << "Another line added to this file."; outFile.close(); // Close the file after writing } else { std::cerr << "Unable to open file"; // Error handling when opening fails } return 0; } ``` 这段程序会尝试打开名为 `example.txt` 的新文件,并向其中写入两行字符串数据。如果文件已经存在,则会被覆盖;若不存在,则自动创建该文件[^2]。 #### 使用 `ofstream` 处理二进制文件 对于更复杂的数据存储需求,比如保存图像或其他非文本格式的内容时,可以采用二进制方式来处理文件: ```cpp #include <iostream> #include <fstream> struct DataRecord { int id; double value; }; int main() { const char* filename = "datafile.dat"; // Create and write data into binary file std::ofstream binOut(filename, std::ios::out | std::ios::binary); if (!binOut) { std::cerr << "Error creating or accessing '" << filename << "'\n"; return -1; } DataRecord record{42, 3.14}; binOut.write(reinterpret_cast<char*>(&record), sizeof(DataRecord)); binOut.close(); return 0; } ``` 此代码片段展示了怎样利用 `std::ofstream` 和二进制模式 (`std::ios::binary`) 来序列化结构体对象到磁盘上的二进制文件中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值