文件操作实例:使用Java进行文件读写的基本操作案例?

原创 雨点打透心脏的1/2处 2024-10-08 03:24 133阅读 0赞

在Java中,我们可以使用java.io包中的类来进行文件的读写。以下是一些基本的操作案例:

  1. 创建文件
    ```java
    import java.io.File;

// 创建一个新的文本文件
File file = new File(“myFile.txt”);
if (!file.createNewFile()) {
System.out.println(“Failed to create file.”);
} else {
System.out.println(“File created successfully.”);
}

  1. 2. **读写文件内容**:
  2. ```java
  3. import java.io.*;
  4. // 读取文件内容
  5. File file = new File("myFile.txt");
  6. try (BufferedReader br = new BufferedReader(new FileReader(file)))) {
  7. String line;
  8. while ((line = br.readLine()) != null) {
  9. System.out.println(line);
  10. }
  11. } catch (IOException e) {
  12. e.printStackTrace();
  13. }
  14. // 写入文件内容
  15. String content = "Hello, World!";
  16. file = new File("myFile.txt");
  17. try (PrintWriter writer = new PrintWriter(new FileWriter(file)))) {
  18. writer.write(content);
  19. writer.close();
  20. } catch (IOException e) {
  21. e.printStackTrace();
  22. }

以上就是使用Java进行文件读写的基本操作案例。

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

发表评论

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

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

相关阅读