理解Java标准库中的IO操作:文件读写示例

原创 向右看齐 2024-11-14 17:06 103阅读 0赞

在Java中,标准库中的java.io包提供了各种类型的输入/输出流,用于进行文件读写等IO操作。

以下是一个简单的文件读写示例:

  1. 文件写入:
    ```java
    import java.io.*;

public class FileWriteExample {
public static void main(String[] args) {
String content = “Hello, World!”; // 要写入的文本

  1. try (FileWriter writer = new FileWriter("myFile.txt")); // 创建一个FileWriter对象,指定要写的文件名
  2. writer.write(content); // 将内容写入到文件中
  3. } catch (IOException e) {
  4. System.out.println("Error occurred while writing to file: " + e.getMessage());
  5. }
  6. }

}

  1. 2. 文件读取:
  2. ```java
  3. import java.io.*;
  4. public class FileReadExample {
  5. public static void main(String[] args) {
  6. String content;
  7. try (FileReader reader = new FileReader("myFile.txt")); // 创建一个FileReader对象,指定要读取的文件名
  8. content = new String(reader.read()); // 从文件中读取一行内容(这里只读取了一行)
  9. } catch (IOException e) {
  10. System.out.println("Error occurred while reading from file: " + e.getMessage());
  11. }
  12. if (content != null && !content.isEmpty()) {
  13. System.out.println(content);
  14. }
  15. }
  16. }

以上示例展示了如何使用Java标准库中的FileWriterFileReader进行文件读写操作。

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

发表评论

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

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

相关阅读