Java中IO流操作问题:读写文件示例

原创 太过爱你忘了你带给我的痛 2024-12-10 21:00 152阅读 0赞

在Java中,IO流主要用于处理输入输出。以下是一个读写文件的简单示例:

  1. 创建一个File对象
    ```java
    import java.io.File;

String fileName = “example.txt”; // 文件名
File file = new File(fileName); // 创建File对象

  1. 2. **检查文件是否存在**:
  2. ```java
  3. if (!file.exists()) {
  4. System.out.println("File does not exist.");
  5. } else {
  6. System.out.println("File exists.");
  7. }
  1. 读取文件内容

    1. try {
    2. String content = new String(file.readAllBytes()));
    3. System.out.println("Content of file: " + content);
    4. } catch (IOException e) {
    5. System.out.println("Error reading file: " + e.getMessage());
    6. e.printStackTrace();
    7. }
  2. 写入文件内容

    1. try {
    2. String newData = "This is the new content.";
    3. // 将字符串转换为字节数组
    4. byte[] bytesToWrite = newData.getBytes();
    5. // 写入新的内容到原文件
    6. file.writeAll(bytesToWrite));
    7. System.out.println("Content updated successfully.");
    8. } catch (IOException e) {
    9. System.out.println("Error updating file: " + e.getMessage());
    10. e.printStackTrace();
    11. }

以上就是Java中读写文件的基本示例。在实际开发中,可能会遇到更多错误和异常情况,需要进行适当的处理。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,152人围观)

还没有评论,来说两句吧...

相关阅读