Java文件操作:读写文件内容,以及文件路径处理的示例

原创 一时失言乱红尘 2024-10-07 21:48 127阅读 0赞

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

  1. 读取文件内容
    ```java
    import java.io.File;
    import java.io.IOException;

public class ReadFile {
public static void main(String[] args) {
String fileName = “example.txt”; // 文件名

  1. File file = new File(fileName); // 创建File对象
  2. try {
  3. // 读取文件内容
  4. String content = new String(file.readAllBytes()));
  5. System.out.println("Content of file: " + content);
  6. } catch (IOException e) {
  7. e.printStackTrace();
  8. }
  9. }

}

  1. 2. **写入文件内容**:
  2. ```java
  3. import java.io.File;
  4. import java.io.IOException;
  5. public class WriteFile {
  6. public static void main(String[] args) {
  7. String fileName = "example.txt"; // 文件名
  8. String content = "Hello, World!"; // 要写入的内容
  9. File file = new File(fileName); // 创建File对象
  10. try {
  11. // 写入文件内容
  12. file.createNewFile();
  13. byte[] bytes = content.getBytes("UTF-8"); // 使用UTF-8编码
  14. file.write(bytes);
  15. System.out.println("Content written to file: " + content);
  16. } catch (IOException e) {
  17. e.printStackTrace();
  18. }
  19. }
  20. }
  1. 文件路径处理
    ```java
    import java.io.File;

public class FilePathHandling {
public static void main(String[] args) {
// 创建一个相对路径
String relativeFilePath = “resources/example.txt”;

  1. // 使用File类的构造方法创建File对象
  2. File file = new File(relativeFilePath);
  3. // 检查文件是否存在
  4. if (file.exists()) {
  5. System.out.println("File exists at path: " + file.getAbsolutePath());
  6. } else {
  7. System.out.println("File does not exist at path: " + file.getAbsolutePath()));
  8. }
  9. }

}
```

以上示例涵盖了Java中基本的文件读写操作以及文件路径处理。

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

发表评论

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

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

相关阅读