Java中的IO流:文件读写操作实例

原创 心已赠人 2024-11-23 06:12 44阅读 0赞

在Java中,IO(Input/Output)流用于处理各种类型的输入和输出操作,包括文件读写。以下是一些典型的文件读写操作实例:

  1. 文件的创建
    ```java
    File file = new File(“myfile.txt”); // 创建一个表示文件的新File对象

// 如果文件不存在,则尝试创建它
if (!file.exists()) {
boolean created = file.createNewFile(); // 使用createNewFile方法创建新文件
if (created) { // 如果成功创建文件,打印提示信息
System.out.println(“File created successfully: “ + file.getAbsolutePath());
}
} else { // 如果文件已经存在,直接读取或写入
System.out.println(“File already exists: “ + file.getAbsolutePath());
}
}

  1. 2. **文件的读取**:
  2. ```java
  3. try (BufferedReader br = new BufferedReader(new FileReader(file)))) {
  4. String line;
  5. while ((line = br.readLine()) != null) { // 逐行读取
  6. System.out.println(line);
  7. }
  8. } catch (IOException e) {
  9. System.err.println("Error reading file: " + e.getMessage());
  10. e.printStackTrace();
  11. }
  1. 文件的写入
    1. try (PrintWriter writer = new PrintWriter(new FileWriter(file)))) {
    2. writer.print("Hello, World!\n"); // 写入内容
    3. } catch (IOException e) {
    4. System.err.println("Error writing file: " + e.getMessage());
    5. e.printStackTrace();
    6. }

以上就是Java中文件读写操作的基本实例,包括创建、读取和写入等流程。

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

发表评论

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

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

相关阅读